我注意到官方 Node 文档对 fs.exists
的描述令人吃惊:
"fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.
In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there."
我理解这个建议,打开一个文件,如果它不存在则处理错误,但我不明白为什么接口(interface)被弃用而不是实现简单地改变。
谁能向我解释为什么使用像 fs.exists
一样简单和合乎逻辑的 API 来检查文件是否存在是一件很糟糕的事情,以至于它应该被称为反模式并从 Node API 中删除?
最佳答案
没有必要使用 fs.stat(),因为 fs.existsSync() 还没有被弃用。
https://nodejs.org/api/fs.html#fs_fs_existssync_path
fs.existsSync(path)
Added in: v0.1.21 path | Synchronous version of fs.exists(). Returns true if the file exists, false otherwise.
Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback >parameter to fs.exists() accepts parameters that are inconsistent with other >Node.js callbacks. fs.existsSync() does not use a callback.)
关于node.js - fs.exists、fs.existsSync - 为什么不推荐使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28532820/