我正在阅读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.stat
和 fs.access
都不推荐用于特殊情况在打开文件之前检查文件的可访问性。正如问题中提到的那样,这可能会触发竞争条件。函数 exists()
和 existsSync()
由于这个原因(以及其他一些与 API 相关的原因)被弃用(大约版本 4):它们经常被利用目的。
当试图打开文件时,如果文件不可访问,该操作将触发错误。因此,此类检查应在此处处理。否则,有 more than one reasonable way to check if a file exists .
另请注意,从版本 6.8.0 开始,existsSync()
已被弃用!参见 discussion和 6.8.0 changelog .上述规则同样适用:只有在您之后不打算打开文件时才使用它。
关于javascript - 为什么不推荐使用 fstat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40259928/