electron + vue3 + ts 手动保存/读取本地文件

1. 在src/main/index.ts中添加文件操作相关IPC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 文件操作 IPC
// 处理保存文件的IPC请求
ipcMain.handle('save-file', async (_, { content }: { content: string }) => {
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
title: '保存文件',
defaultPath: join(app.getPath('documents'), 'example.txt')
})
if (!canceled && filePath) {
fs.writeFileSync(filePath, content, 'utf-8')
return filePath
}
return null
})

// 处理读取文件的IPC请求
ipcMain.handle('read-file', async () => {
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
title: '打开文件',
defaultPath: app.getPath('documents'),
properties: ['openFile'],
filters: [{ name: '文本文件', extensions: ['txt'] }]
})
if (!canceled && filePaths.length > 0) {
const content = fs.readFileSync(filePaths[0], 'utf-8')
return { filePath: filePaths[0], content }
}
return null
})

2. 在src/preload/index.ts中的自定义api内暴露相关接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 自定义 api
const api = {
/**
* 将内容保存到文件中
* @param content 要保存的文件内容
* @returns 返回保存操作的 Promise 结果
*/
saveFile: (content: string) => ipcRenderer.invoke('save-file', { content }),

/**
* 读取文件内容
* @returns 返回一个包含文件内容的 Promise 对象
*/
readFile: () => ipcRenderer.invoke('read-file')
}

3. 构建ts操作文件,vue调用函数即可手动本地操作文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 本地文件数据
*/
type localFileData = {
path: string // 文件路径
content: string // 文件内容
}

/**
* 保存文件
* @param content 文件内容
* @returns 保存的文件路径或 null
*/
const saveFile = async (content: string): Promise<string | null> => {
return await (window as any).api.saveFile(content)
}

/**
* 读取文件
* @returns 读取的文件内容和路径或 null
*/
const readFile = async (): Promise<localFileData | null> => {
return await (window as any).api.readFile()
}

export default { saveFile, readFile }