node.js - nodejs fs.exists() 和 fs.existsAsync() 已弃用,但为什么我仍然可以在 Node v4 和 v6 中使用它

标签 node.js fs

我正在这里阅读 Nodejs 文档 https://nodejs.org/api/fs.html#fs_fs_exists_path_callback

它说 fs.exists()fs.existsAsync() 已弃用。

所以我的直觉是,如果我使用较新版本的 NodeJs,它会抛出错误。

但是,使用 NodeJs v4.3.2 和 v6,我仍然看到 fs.exists() 工作。为什么会这样呢?这是否意味着如果我从 NodeJS v0.10.0 迁移系统,我不一定需要更新调用此类函数的依赖项,并且它是向后兼容的?

最佳答案

这意味着 Node.js 开发背后的社区现在建议不要使用此功能,因为它存在问题,他们可能会在未来某个时候删除它,以迫使人们停止使用它。

So my intuition would be that it will throw an error if I am using a newer version of NodeJs.

他们还没有让它抛出错误。

However, using both NodeJs v4.3.2 and v6, I still see the fs.exists() working. why is it so?

并且,从您的问题标题来看:

but why can I still use it with Node v4 and v6?

因为虽然他们现在建议不要使用它,但他们还没有删除它。

does that mean that If I migrate my system from NodeJS v0.10.0, I don't necessarily have to update my dependencies that is invoking such function, and it's backward compatible?

没有。 Node.js 背后的社区告诉您,他们保留在任何 future 版本中删除这两个功能的权利。

底线:如果您想与 future 版本兼容,请停止使用 fs.exists()现在。

<小时/>

fs.exists()与其他 Node.js 异步 API 也不一致,因为回调不遵循 fn(err, data) 的典型调用约定。 。它没有 err参数使其变得奇怪。

您可能还想了解它们使用时出现问题的原因。现代操作系统是一个多任务系统,文件系统是潜在许多进程之间的共享资源。这意味着如果您这样做:

if (fs.existsSync("somefile")) {
    // execute some code when somefile does exist 
} else {
    // execute some code when somefile does not exist
}

然后,某个文件是否存在的状态可能会在您运行 fs.existsSync() 之间发生变化。调用以及执行假设知道文件是否存在的代码的时间。这被称为“竞争条件”,它被认为是非常糟糕的设计,因为它可能会出现极难重现的错误,这些错误可能只是偶尔出现(可能是试图找到的最糟糕的错误类型)。

直接从 fs.exists() 的 Node.js 文档中注意这一点:

Using fs.exists() to check for the existence 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 does not exist.

如果您使用的是异步版本fs.exists() ,那么竞争条件会更糟,因为您自己的 Node.js 代码甚至可能会因为您的 if/else 逻辑运行而更改文件的状态。

根据您通常尝试执行的操作,非竞争条件替代方法是尝试使用某种独占访问权限打开文件。如果文件存在,您将成功打开它,没有竞争条件。如果该文件不存在,您只会收到一个错误,然后您可以处理该错误。在其他一些情况下,您只是尝试使用某种模式创建文件,如果该文件已存在,则会失败。这两种情况都在操作系统文件系统代码内使用原子比较,因此它们没有“竞争条件”。

您现在应该修复您的代码。如果您仍然不明白建议的修复是什么,请发布您使用 fs.exists() 的代码以及周围的代码上下文,我们可以帮助您进行更好的设计。

关于node.js - nodejs fs.exists() 和 fs.existsAsync() 已弃用,但为什么我仍然可以在 Node v4 和 v6 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43240143/

相关文章:

node.js - 无法读取属性 'indexOf' socketiojwt

javascript - 可以在没有 Node.js 的情况下使用 Twilio 可编程视频吗?

node.js - 在对话 Node alexa-sdk 期间更改卡

node.js - 带锁的读取流 (NodeJS)

node.js - Node JS - 我无法同步使用 FS.Stat

arrays - Mongoose 从 findByIdAndUpdate 中删除数组(继承模式)

javascript - TypeScript 包创建声明文件

javascript - Node.js 错误 ENOENT,未更改任何内容时打开 "file/path"

node.js - 如何在具有可写流的循环中顺序在 Node 中写入流?

node.js - nodeJs脚本可以删除自己的文件吗?