アプリケーションの設定ファイル(config.json や settings.toml など)を保存するための推奨ディレクトリパスを取得する方法を解説します。
Tauri では @tauri-apps/api/path の appConfigDir を使用することで、OS の慣習に従った適切な場所(Windows の Roaming、macOS の Application Support 等)を簡単に特定できます。
前提条件
この機能を使用するには、@tauri-apps/api パッケージおよび @tauri-apps/plugin-fs プラグインが必要です。
1. プラグインのインストール
プロジェクトのルートディレクトリで以下のコマンドを実行してプラグインを追加します。
npm run tauri add fs
2. Permissions (権限) の設定
src-tauri/capabilities/default.json に以下の権限を追加します。
{
"permissions": [
...,
{
"identifier": "fs:allow-exists",
"allow": [{ "path": "$APPCONFIG" }, { "path": "$APPCONFIG/**" }]
},
{
"identifier": "fs:allow-mkdir",
"allow": [{ "path": "$APPCONFIG" }, { "path": "$APPCONFIG/**" }]
},
{
"identifier": "fs:allow-read-text-file",
"allow": [{ "path": "$APPCONFIG/**" }]
},
{
"identifier": "fs:allow-write-text-file",
"allow": [{ "path": "$APPCONFIG/**" }]
}
]
}
※ 上記の例では $APPCONFIG(BaseDirectory.AppConfig)そのもの、および配下でのファイル操作を許可しています。アクセスするディレクトリに応じて、パス変数を指定してください。スコープが設定されていないディレクトリにはアクセスできません。
使用方法
@tauri-apps/api/path から appConfigDir をインポートして使用します。
OSごとの保存先例
tauri.conf.json の identifier が com.example.app の場合:
| OS | パス (例) | 用途 |
|---|---|---|
| Windows | C:\Users\{User}\AppData\Roaming\com.example.app | ユーザーごとの設定、ローミングプロファイル対応データ |
| macOS | /Users/{User}/Library/Application Support/com.example.app | アプリケーション設定、サポートデータ |
| Linux | /home/{user}/.config/com.example.app | XDG Base Directory Specification に準拠した設定場所 |
1. フロントエンドから作成する (TypeScript)
@tauri-apps/api/path の appConfigDir 関数を使用します。
設定ディレクトリのパスを表示する
import { appConfigDir } from '@tauri-apps/api/path';
async function showConfigPath() {
try {
const configDir = await appConfigDir();
console.log('Config Directory:', configDir);
} catch (err) {
console.error('Failed to get config path:', err);
}
}
設定ファイルの保存場所として使用する
設定ディレクトリを取得し、そこに settings.json を保存する実践的なフローです。
ディレクトリが存在しない場合に作成する処理を含みます。
import { appConfigDir, join } from '@tauri-apps/api/path';
import { writeTextFile, mkdir, exists } from '@tauri-apps/plugin-fs';
// 保存したい設定データ
const userSettings = {
theme: 'dark',
notifications: true,
lastLogin: new Date().toISOString()
};
async function saveSettings() {
try {
// 1. 設定ディレクトリのパスを取得
const configPath = await appConfigDir();
// 2. ディレクトリが存在するか確認し、なければ作成
const dirExists = await exists(configPath);
if (!dirExists) {
await mkdir(configPath, { recursive: true });
}
// 3. ファイルパスを結合
const filePath = await join(configPath, 'settings.json');
// 4. JSONとして保存
await writeTextFile(filePath, JSON.stringify(userSettings, null, 2));
console.log('Settings saved to:', filePath);
return filePath;
} catch (err) {
console.error('Error saving settings:', err);
}
}
設定ファイルの読み込み
保存した設定ファイルを読み込みます。
import { appConfigDir, join } from '@tauri-apps/api/path';
import { readTextFile, exists } from '@tauri-apps/plugin-fs';
async function loadSettings() {
try {
const configPath = await appConfigDir();
const filePath = await join(configPath, 'settings.json');
if (await exists(filePath)) {
const content = await readTextFile(filePath);
const settings = JSON.parse(content);
console.log('Loaded settings:', settings);
return settings;
} else {
console.log('Settings file not found. Using defaults.');
return null; // またはデフォルト設定を返す
}
} catch (err) {
console.error('Error loading settings:', err);
}
}
2. バックエンドから作成する (Rust)
Rust では AppHandle を通じてパスを取得します。
設定ディレクトリパスの取得
use tauri::Manager;
#[tauri::command]
fn get_config_dir(app: tauri::AppHandle) -> Result<String, String> {
app.path().app_config_dir()
.map(|p| p.to_string_lossy().to_string())
.map_err(|e| e.to_string())
}
設定ファイルの初期化
use tauri::Manager;
use std::fs;
#[tauri::command]
fn init_config(app: tauri::AppHandle) -> Result<(), String> {
let config_dir = app.path().app_config_dir().map_err(|e| e.to_string())?;
if !config_dir.exists() {
fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?;
}
let config_path = config_dir.join("settings.json");
if !config_path.exists() {
fs::write(config_path, r#"{ "theme": "light" }"#).map_err(|e| e.to_string())?;
}
Ok(())
}
補足
appConfigDir: アプリケーション固有の設定データを保存する標準的な場所です。Windows ではRoamingに配置されるため、ドメインネットワーク環境などでユーザープロファイルと共にローミングされます。appLocalDataDirとの違い:appLocalDataDirはローカルキャッシュやデータベースなど、同期されるべきでない(サイズが大きい、またはマシン固有の)データを保存するために使用します。