electron 在主进程里用nodejs读取的文件内容无法传给渲染进程 什么情况?
通过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吗
回复
1个回答

test
2024-07-11
没 return
出去啊
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 // 你的 return 在这
}
})
// 这是外层函数,出得去才怪了
}
可以改成 Promise
function readFile(event, filePath){
return new Promise((res, rej) => {
fs.readFile(filePath, { encoding: "utf-8" }, (err, result) => {
if (err) {
rej(err)
} else {
res(result)
}
})
})
}
或者用很棒的 fs/promises
import fs from 'fs/promises'
function readFile(event, filePath) {
return fs.readFile(filePath, { encoding: "utf-8" }) // .then(...)
}
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容