fs.FileRead -> TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串、缓冲区或 URL 类型之一。接收类型未定义

Sun*_*the 2 javascript fs node.js electron

function openFileDialog() {
  dialog.showOpenDialog(win, {
    properties: ['openFile']
  } , filepath  => {

    if (filepath) {
      fs.writeFile('path.txt', filepath, function (err, data) {
        if (err) console.log(err);
      });
      scanFile(filepath)
    }
  })
}

function scanFile(filepath) {
  if(!filepath || filepath[0] == 'undefined') return;
  console.log(filepath)
  fs.readFile(filepath,"utf8", (err,data) => { // ----> *ERROR*
    if(err) console.log(err);
    var arr = [];
    if (data.substr(-4) === '.mp3' || data.substr(-4) === '.m4a'
    || data.substr(-5) === '.webm' || data.substr(-4) === '.wav'
    || data.substr(-4) === '.aac' || data.substr(-4) === '.ogg'
    || data.substr(-5) === '.opus') {
    arr.push(files[i]);
  }
  var objToSend = {};
    objToSend.files = arr;
    objToSend.path = filepath;

    win.webContents.send('selected-files', objToSend)
  })  
}  
Run Code Online (Sandbox Code Playgroud)

我试图制作电子音乐播放器应用程序。第一步是打开我的文件。当我打开文件时,"TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type undefined" 错误发生并且错误消息显示 scanFile(filepath), fs.readFile(~ ~) 导致错误。我该如何解决?

djh*_*eru 6

第一行scanFile写着:

if(!filepath || filepath[0] == 'undefined') return;

这向我表明这filepath是一个数组,而不是一个字符串(或缓冲区或 URL)。检查console.log语句的输出以查看是否是这种情况。由于该if语句正在检查filepath[0],我将从那里开始并更新代码以读取fs.readFile(filepath[0],"utf8", (err,data) => {,因为该if语句暗示filepath[0] 是您应该使用的值