通过preload.js暴露出 readFile 这个方法
contextBridge.exposeInMainWorld('fileApi', {
openFile: () => ipcRenderer.invoke('dialog:openFile'),
readFile:(path) => ipcRenderer.invoke('node:readFile',path),
});
在渲染进程中调用 readFile
async readFile () {
const fileContent = await window.fileApi.readFile(this.filePath);
console.log("fileContent", fileContent);
},
然后出发main.js里面的
function readFile(event,filePath){
fs.readFile(filePath, { encoding: "utf-8" }, (err, result) => {
if (err) {
console.log( "读取文件内容失败");
return false
} else {
console.log('result--->',result)
return result
}
})
}
终端是可以打印出读取的本地文件内容的 也就是 result这个值
但是return给渲染进程
async readFile () {
const fileContent = await window.fileApi.readFile(this.filePath);
console.log("fileContent", fileContent);
},
这个fileContent确实undefined..
main.js里面如果改成这样 就可以return出去
function readFile(event,filePath){
return '读取文件内容...'
}
这是什么情况??nodejs的fs.readFile 获取的内容不可以return吗
没
return
出去啊可以改成
Promise
或者用很棒的
fs/promises