node.js - 电子中的奇怪错误。未捕获的异常: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);
}
尝试恢复到旧版本等。无济于事。
感谢您的任何建议。
解决方案
在这里小心,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 主线程。
推荐阅读
- ember.js - Ember 从子组件中移除父类
- javascript - Java/Javascript/JSP 中的下拉选项
- css - 有人可以解释一下什么是 flex 属性吗?
- php - array_push() 实际期望多少个参数?
- terraform - Terraform(提供者 AWS)- Auto Scaling 组不会在启动模板更改时生效
- aurelia - Aurelia 启动错误 - 资源路径无效:函数 Compose
- python - data["comment"].str.contains 花费了很多时间
- javascript - 如何获取学生数据的每个上传文件的文件名
- python - 在另一个列表的元素指定的范围内计算列表中元素数量的更快方法
- c# - 自定义 ListView 项目在第一个 SubItems 列位置重复