Node.js fs.stat 和 fs.readFileSync 之间的错误处理相关性

Node.js error-handle relevance between fs.stat and fs.readFileSync

首先,抱歉我的英语不好,感谢您点击这个问题。

我想用Node.js代码读取一些文件

为此,首先,我必须检查文件是否存在。

所以我用了fs.stat

然后,我想同步读取文件。

所以我用了fs.readFileSync

我的问题是 尽管我处理了 fs.stat 的错误,我是否应该处理 [=44= 的错误] 分开 ?

下面是代码

  fs.stat('./fooData.json', function(err, stat){
    if(err === null){ // <-- on this point, fooData.json's existence is confirmed.
      try{ // <-- should I error-handle for readFilesync again ?
        let oldData = fs.readFileSync('./fooData.json');
      }
      catch(e){
        console.log(e); // file read error handle
      }
    }

是的,你应该这样做,因为调用 fs.stat 并不能保证在调用 fs.readFileSync 时文件存在,而且它也不能保证你可以读取这个文件(没有权限和依此类推)。

官方Node.js文档不建议在fs.readFileSync之前使用fs.stat:

Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.

fs.stat