如何确定fs.Stats对象中是否存在文件?

时间:2013-11-16 05:00:40

标签: linux node.js filesystems stat

我的意思是,基本上就是这样。 nodejs文档声明exists是一种anachonism,但我看不出stat如何替换它。

1 个答案:

答案 0 :(得分:1)

fs.stat()方法实际上并不替换fs.exists(),但您可以通过其他函数的错误代码查明文件是否存在。无论文件是否存在,您都可以直接在文件上使用fs.stat()。同样的事情也适用于fs.open()fs.readFile()等。

fs.stat(file, function(err, stats) {
  // if err is ENOENT
});

文档建议这样做,因为它消除了在fs.exists()调用和实际文件操作之间发生竞争条件的可能性,其中文件可以在异步函数之间被删除。


这是直接检查文件是否存在的示例,如果存在,则读取它。如果文件不存在,err对象的code属性将包含字符串ENOENT

fs.readFile('/etc/passwd', function(err, data) {
  if (err.code == 'ENOENT') {
    // the file doesn't exist
  }

  // the file exists if there are no other errors
});
相关问题