node.js - fs.exists、fs.existsSync - 为什么不推荐使用它们?

标签 node.js

我注意到官方 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/

相关文章:

node.js - Mongoose 单个应用程序的多个数据库

javascript - 使用 fs.writeFile 将 javascript 代码写入 js

javascript - 可排序用户列表最佳实践

node.js - Nodejs/rails/主干架构

node.js - express.js 对 http 请求的错误处理

javascript - 如何知道 node-webkit 应用程序是否以管理员/提升权限运行?

node.js - NodeJS/Express/MongoDB - 如何限制 POST 请求中接受的参数?

node.js - 如何在自定义 Jade 过滤器中渲染 block ?

node.js - JWT token 中应包含多少个人资料数据?

mysql - Node mysql 错误 : connect ECONNREFUSED