tauri嵌入自定义目录/文件,并在代码中读取文件内容的操作流程

196 阅读1分钟

可以看官方文档:Embedding Additional Files | Tauri Apps

在绑定了文件之后,可以在js中访问嵌入的文件或者在rust中读取嵌入的文件内容,详细的配置操作如下。

在src-tauri中创建自定义文件夹或文件,并在在tauri.conf.json中配置嵌入:

例如我这里文件内容如下:

然后就可以在代码中读取这个文件了。

在js中读取文件的操作:

import { resolveResource } from '@tauri-apps/api/path'
import { readTextFile } from '@tauri-apps/api/fs'


const resourcePath = await resolveResource('data/example.json')
const langDe = JSON.parse(await readTextFile(resourcePath))
console.log(langDe)

在rust中读取文件的操作:

#[tauri::command]
pub async fn read_json_file(handle: tauri::AppHandle) -> String {
    let resource_path = handle
        .path_resolver()
        .resolve_resource("data/example.json")
        .expect("failed to resolve resource");
    let file = std::fs::File::open(&resource_path).unwrap();
    let lang_de: serde_json::Value = serde_json::from_reader(file).unwrap();
    return lang_de.to_string();
}



在前端中调用这个函数:
try {
        const jsonContent: any = await invoke('read_json_file')
        const data = JSON.parse(jsonContent)
        console.log('json data:', data)
    } catch (error) {
        console.error('Error reading JSON file:', error)
    }

 

读取到的结果: