作为 Electron 开发者,我们习惯了使用 Node.js 的 fs 模块来处理文件操作。在 Tauri 2.0 中,文件系统操作被重新设计,采用了 Rust 的安全特性和权限系统。本文将帮助你理解和重构这部分功能。
文件操作对比
Electron 的文件操作
在 Electron 中,我们通常这样处理文件:
// main.js
const fs = require('fs').promises
const path = require('path')
// 读取文件
async function readFile(filePath) {
try {
const content = await fs.readFile(filePath, 'utf8')
return content
} catch (error) {
console.error('Failed to read file:', error)
throw error
}
}
// 写入文件
async function writeFile(filePath, content) {
try {
await fs.writeFile(filePath, content, 'utf8')
} catch (error) {
console.error('Failed to write file:', error)
throw error
}
}
// 列出目录内容
async function listDirectory(dirPath) {
try {
const files = await fs.readdir(dirPath)
return files
} catch (error) {
console.error('Failed to list directory:', error)
throw error
}
}
主要特点:
- 直接访问文件系统
- 无权限限制
- 同步/异步操作
- 完整的 Node.js API
Tauri 的文件操作
Tauri 采用了更安全的方式:
// main.rs
use std::fs;
use tauri::api::path;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize)]
struct FileEntry {
name: String,
path: String,
is_file: bool,
size: u64,
}
#[tauri::command]
async fn read_file(path: String) -> Result<String, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
}
#[tauri::command]
async fn write_file(path: String, content: String) -> Result<(), String> {
fs::write(path, content)
.map_err(|e| e.to_string())
}
#[tauri::command]
async fn list_directory(path: String) -> Result<Vec<FileEntry>, String> {
let mut entries = Vec::new();
for entry in fs::read_dir(path).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let metadata = entry.metadata().map_err(|e| e.to_string())?;
entries.push(FileEntry {
name: entry.file_name().to_string_lossy().into_owned(),
path: entry.path().to_string_lossy().into_owned(),
is_file: metadata.is_file(),
size: metadata.len(),
});
}
Ok(entries)
}
// fileSystem.ts
import { invoke } from '@tauri-apps/api/tauri'
import { BaseDirectory, createDir, readDir } from '@tauri-apps/api/fs'
interface FileEntry {
name: string
path: string
isFile: boolean
size: number
}
// 读取文件
export const readFile = async (path: string): Promise<string> => {
try {
return await invoke('read_file', { path })
} catch (error) {
console.error('Failed to read file:', error)
throw error
}
}
// 写入文件
export const writeFile = async (path: string, content: string): Promise<void> => {
try {
await invoke('write_file', { path, content })
} catch (error) {
console.error('Failed to wri

最低0.47元/天 解锁文章
1915

被折叠的 条评论
为什么被折叠?



