主进程
import { ipcMain, dialog } from 'electron';
// 忽略其他...
ipcMain.on('open-file-dialog', (event) => {
dialog
.showOpenDialog({
filters: [{ name: '文件类型', extensions: ['xlsx'] }],
})
.then((res) => {
event.sender.send('selected-path', res.filePaths);
})
.catch(console.log);
});
渲染进程
import { ipcRenderer } from 'electron';
import fs from 'fs';
import Excel from 'exceljs';
// 忽略其他逻辑...
const handleSelectFile = () => {
ipcRenderer.send('open-file-dialog');
//注册一次监听事件,之后注销此监听事件
ipcRenderer.once('selected-path', async (_event: any, paths: Array<string>) => {
if (!paths[0]) return;
const buffer = fs.readFileSync(paths[0]);
// 其他操作
});
};
避坑
在使用ipcRenderer监听时,监听函数可能会出现多次调用的情况:
import { ipcRenderer } from 'electron';
import fs from 'fs';
import Excel from 'exceljs';
// 忽略其他逻辑...
const handleSelectFile = () => {
ipcRenderer.send('open-file-dialog');
// 监听和发送放在同一个函数中。
// 原因可能是组件更新导致函数调用,写在同一函数中可以避免此类问题。
};
// 注册监听事件,不会注销,注册好后会重复多次调用监听函数,once也是一样效果
// 正确做法同上
ipcRenderer.on('selected-path', async (_event: any, paths: Array<string>) => {
if (!paths[0]) return;
const buffer = fs.readFileSync(paths[0]);
// 其他操作
});