javascript - Electron 从对话框读取文件得到类型错误

标签 javascript node.js electron

我正在编写一个 Electron 程序,该程序需要读取一个文件才能应用另一个程序。现在,我只希望它成功读取并记录文件的内容。
这是我在名为script.js的脚本中使用的代码,该脚本包含在index.html中的脚本标签中

// dialog box
const { dialog } = require('electron').remote;
// file system, needed to read contents of the ecgFile
const {fs} = require('fs');

const dialogOptions = {properties:['openFile']}

// bool for checking if file has been selected
let isFileSelected = false;
let ecgFile; // content of the ecgFile itself

// Buttons
const openFileBtn = document.getElementById('openFileBtn');

// on click event, opens the dialog box and loads content of the file
openFileBtn.onclick = () =>
{
  console.log("start")

  let filePathArray = dialog.showOpenDialogSync({properties: ['openFile']}) // output the filepath of the file selected
  let filePath = filePathArray[0] // set to the first object in the array, which is what is needed
  console.log("File Location -- "+ filePath) // print to check its hunky dory
  readFile(filePath) // read the file
  console.log("End")
};

function readFile(filePath) 
{
  fs.readFile(filePath,{"encoding": "utf8"},(err,data) =>
  {
    if (err)
    {
      console.log("Cannot read file",err);
      return;
    }
    console.log("Content of data: ")
    console.log(data);    
  }
  )
}

我能够成功打印要使用的filePath,问题是当我将该文件传递给readFile函数时
当它运行readFile函数时,它总是输出此错误

Uncaught TypeError: Cannot read property 'readFile' of undefined
    at readFile (script.js:55)
    at HTMLButtonElement.openFileBtn.onclick (script.js:23)

我一直在寻找无法成功的解决方案。谢谢您的时间和帮助

最佳答案

fs导入不能为destructured
代替

const {fs} = require('fs');

const fs = require('fs');

关于javascript - Electron 从对话框读取文件得到类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66135674/

相关文章:

javascript - 链式 promise 和保留 `this`

javascript - 使用 jQuery 单击关闭输入区域功能

javascript - 这个可重用的 AngularJS 服务如何在 mousemove 上更新?

javascript - 循环中嵌套回调

node.js - SailsJS 如何对实例方法和从另一个模型填充的实例方法应用排序?

node.js - 如何在Electron-Forge中成功高效地安装SQLite3?

mysql - 是否可以从 Electron 应用程序将查询发送到在线数据库?

javascript - 如何从 C++ 插件中的 'MediaStream' 对象读取音频数据

javascript - jquery each 在循环时无法正常工作

node.js - 无法删除node-red模块