Search code examples
javascriptnode.jselectronfs

fs.FileRead -> TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type undefined


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)
  })  
}  

I tried to made electron music player app. As a first step is opening my file. When I open file, "TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type undefined" that error occured and error message showed that scanFile(filepath), fs.readFile(~~) caused error. How should I fix it?


Solution

  • The first line of scanFile reads:

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

    This indicates to me that filepath is an array, not a string (or Buffer or URL). Check the output of the console.log statement to see if this is the case. Since the if statement is checking for filepath[0], I'd start there and update the code to read fs.readFile(filepath[0],"utf8", (err,data) => {, since the if statement implies that filepath[0] is the value you should be using