首页 > 解决方案 > 电子中的奇怪错误。未捕获的异常:TypeError [ERR_INVALID_ARG_TYPE]:“路径”

问题描述

嗨,我正在尝试学习有关 Electron 的教程,但是在尝试从我制作的菜单中打开文件时,我不断收到此错误。

未捕获的异常:TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串、缓冲区或 URL 类型之一。接收到的类型未定义...

这是我的功能。

function openFile() {
  // Opens file dialog looking for markdown
  const files = dialog.showOpenDialog(mainWindow, {
    properties: ['openFile'],
    filters: [{ name: 'Markdown', extensions: ['md', 'markdown', 'txt'] }]
  });

  // If no files
  if (!files) return;

  const file = files[0]; // Grabs first file path in array
  // Loads file contents via path acquired via the dialog
  const fileContent = fs.readFileSync(file).toString();
  console.log(fileContent);
}

尝试恢复到旧版本等。无济于事。

感谢您的任何建议。

标签: node.jsreactjselectron

解决方案


在这里小心,showOpenDialog()是一个异步函数并返回一个承诺。

在您的情况下,正确的用法是:

dialog.showOpenDialog(mainWindow, {
    properties: ['openFile'],
    filters: [{ name: 'Markdown', extensions: ['md', 'markdown', 'txt'] }]
}).then(result => {
    const file = result.filePaths[0];
    const fileContent = fs.readFileSync(file).toString();
    console.log(fileContent);
}).catch(err => {
    console.log(err)
});

还可以考虑使用readFile而不是readFileSync避免阻塞 Electron 主线程。


推荐阅读