特定のファイルを削除する方法を紹介します。
一時ファイルのクリーンアップや、ユーザーが削除を選択したデータの消去などに使用します。
前提条件
このレシピを使用するには、@tauri-apps/plugin-fs プラグインが必要です。
1. プラグインのインストール
プロジェクトのルートディレクトリで以下のコマンドを実行してプラグインを追加します。
npm run tauri add fs
2. Permissions (権限) の設定
src-tauri/capabilities/default.json に以下の権限を追加します。
{
"permissions": [
...,
{
"identifier": "fs:allow-exists",
"allow": [{ "path": "$APPLOCALDATA/**" }]
},
{
"identifier": "fs:allow-remove",
"allow": [{ "path": "$APPLOCALDATA/**" }]
}
]
}
※ 上記の例では $APPLOCALDATA(BaseDirectory.AppLocalData)配下の存在確認および削除を許可しています。アクセスするディレクトリに応じて、パス変数を指定してください。スコープが設定されていないディレクトリにはアクセスできません。
1. フロントエンドから作成する (TypeScript)
@tauri-apps/plugin-fs の remove 関数を使用します。
単一ファイルの削除
remove 関数を使用してファイルを削除します。ディレクトリの削除と同じ関数ですが、ファイルの場合は recursive オプションは不要(無視されます)です。
import { remove, BaseDirectory } from '@tauri-apps/plugin-fs';
async function deleteOldFile() {
try {
await remove('old_data.txt', {
baseDir: BaseDirectory.AppLocalData,
});
console.log('ファイルを削除しました');
} catch (err) {
console.error('削除できませんでした:', err);
}
}
存在チェック付き削除
ファイルが存在するか確認してから削除を行う安全なパターンです。
import { remove, exists, BaseDirectory } from '@tauri-apps/plugin-fs';
async function deleteIfExist(filename: string) {
// 削除前に存在確認を行う
const fileExists = await exists(filename, { baseDir: BaseDirectory.AppLocalData });
if (fileExists) {
await remove(filename, { baseDir: BaseDirectory.AppLocalData });
console.log(`${filename} を削除しました`);
} else {
console.log(`${filename} は存在しません`);
}
}
2. バックエンドから作成する (Rust)
Rust の std::fs を使用します。
ファイル削除
use std::fs;
#[tauri::command]
fn delete_file(path: String) -> Result<(), String> {
fs::remove_file(path).map_err(|e| e.to_string())
}
存在チェック付き削除
use std::fs;
use std::path::Path;
#[tauri::command]
fn safe_delete_file(path: String) -> Result<String, String> {
let p = Path::new(&path);
if p.exists() {
fs::remove_file(p).map_err(|e| e.to_string())?;
Ok("Deleted".into())
} else {
Ok("File didn't exist".into())
}
}
補足
remove: ファイル・ディレクトリ共通の削除関数です(JS)。Rust ではremove_fileです。- Scope: フロントエンドから削除する場合、Scope の設定が必要です。
- ゴミ箱: 完全に削除されます。復元が必要な場合は独自のバックアップ機構などを実装してください。