javascript - 为什么不推荐使用 fstat

标签 javascript node.js

我正在阅读stat 方法的手册here它说:

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.

To check if a file exists without manipulating it afterwards, fs.access() is recommended.

所以,我有两个问题:

  • 为什么使用错误处理程序比 fs.stat() 更适合检查文件是否存在?

  • 并且由于我可以使用 fs.access() 检查文件是否存在,使用 error handler 机制仍然是确保文件打开的首选方法吗?

我想我找到了第二个问题的答案:

Using fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.

所以 fs.open() 可能会阻塞其他进程的文件,而 fs.stat()fs.access() 只是请求信息和其他进程仍然可以更改/删除文件。

最佳答案

我认为这里应该明确的是 fs.statfs.access 都不推荐用于特殊情况在打开文件之前检查文件的可访问性。正如问题中提到的那样,这可能会触发竞争条件。函数 exists()existsSync() 由于这个原因(以及其他一些与 API 相关的原因)被弃用(大约版本 4):它们经常被利用目的。

当试图打开文件时,如果文件不可访问,该操作将触发错误。因此,此类检查应在此处处理。否则,有 more than one reasonable way to check if a file exists .

另请注意,从版本 6.8.0 开始,existsSync() 已被弃用!参见 discussion6.8.0 changelog .上述规则同样适用:只有在您之后不打算打开文件时才使用它。

关于javascript - 为什么不推荐使用 fstat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40259928/

相关文章:

javascript - 隐藏除选定的之外的所有 LI

javascript - 表单是否可能无法识别通过 Selenium 自动化输入的值

javascript - 如何在 Three.js 中不在 Canvas 上实际渲染场景的情况下获取场景的像素数据?

node.js - Mongodb - 未知的顶级运算符 : $elemMatch"

node.js - React 路由器、nginx、 Node 、静态文件

javascript - 如果事件没有发生jquery/javascript,如何记录 react 时间?

javascript - 检查 webpack 是否存在依赖关系

node.js - npm install eslint缺少参数错误

javascript - 将 Node.js net.socket 与流式消息协议(protocol)一起使用

javascript - Node.Js 错误 "No ' 请求中存在 Access-Control-Allow-Origin' header ”