如果 NodeJS 中不存在文件,如何 return 清空数组

How to return empty array if file doesn't exists in NodeJS

如果我尝试读取一个不存在的文件,我想要 console.log 一条消息和 return 一个空数组。 getAllNotes 函数触发有效,肯定会抛出错误 no such file or directory, open 'notes.json'

但是,如果我没有在 if 语句中指定 throw err,为什么会抛出错误?其次,为什么我的 console.log 消息没有输出并且空数组没有被 returned?

var getAllNotes = () => {
  console.log("MADE IT TO GET ALL NOTES")
  var notesArray = fs.readFileSync('notes.json', (err, data) => {
    if (err) {
      console.log("There are no notes to display");
      return [];
    } else {
      console.log("DATA",data)
      console.log("MADE IT TO PARSE")
      return JSON.parse(data);
    }
  });
  console.log("INSIDE GET ALL NOTES", notesArray)
};

fs.readFileSync 是一个阻塞调用,不像 fs.readFile 那样接受回调。它只是 returns 文件的内容,见下面的例子:

var fs = require('fs');
var date = fs.readFileSync('myfile', 'utf8');
console.log(data);

当我 运行 你的例子抛出一个异常,因为你提供了一个回调函数,它期望选项参数的字符串或对象。

您可以使用 fs.existsSync(path) 进行阻塞调用,以在尝试读取文件之前检查文件是否存在。

或者,您可以使用 readFile 的非阻塞版本,并像您尝试的那样提供回调。