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这个值
image.png
但是return给渲染进程

   async readFile () {
      const fileContent = await window.fileApi.readFile(this.filePath);
      console.log("fileContent", fileContent);
    },

这个fileContent确实undefined..
image.png
main.js里面如果改成这样 就可以return出去

function readFile(event,filePath){
    return '读取文件内容...'
}

image.png

这是什么情况??nodejs的fs.readFile 获取的内容不可以return吗

阅读 2k
1 个回答

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(...)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题