fs.exists,fs.existsSync – 他们为什么不推荐使用?

我注意到官方的节点文档说fs.exists令人吃惊:

“fs.exists()是不合时代的,只是出于历史的原因而存在,几乎没有理由在你的代码中使用它。

特别是,在打开文件之前检查文件是否存在是一种反模式,使您容易受到竞争状况的影响:另一个进程可能会在调用fs.exists()和fs.open()之间删除文件。 只要打开文件,并在不存在的时候处理错误。“

我理解的build议,打开一个文件,然后处理错误,如果它不存在,但我不明白的是为什么接口被弃用,而不是简单的改变实现。

任何人都可以向我解释为什么检查一个与fs.exists一样简单和逻辑的api文件的存在是如此糟糕的事情,它应该被称为反模式,并从节点API中删除?

我认为这是因为它是多余的。 您可以通过尝试打开文件来检查文件是否存在。 如果它不存在,它会给你ENOENT

 > fs.open('foo', 'r', function(err, fd) { ... console.log(err, fd); ... }) undefined > { [Error: ENOENT, open 'foo'] errno: 34, code: 'ENOENT', path: 'foo' } undefined 

因为你引用了第二段。

检查文件是否存在没有意义,因为在检查之后它总是可以被删除。

被弃用,因为它是一种反模式。 也就是说,信任exists()然后对文件做些什么是不安全的,因为文件可以在exists-call和doing-something-call之间移除。

我同意上述情况。 但对我来说,存在更多的使用()。 我将空虚拟文件放在我的临时目录和caching目录中。 当我执行危险操作时,比如从caching目录中删除旧文件,我寻找我的虚拟文件,以确保我没有在错误的目录中操作。 即我只需要确认该文件在那里。 存在适合这个完美的法案,但我想我会切换到使用stat()来代替。

existsSync的实现是这样的(v0.10.25):

 function (path) { try { nullCheck(path); binding.stat(pathModule._makeLong(path)); return true; } catch (e) { return false; } } 

所以如果你像if(fs.existsSync(thepath)){}那样编写程序,最好把它改成if(fs.statSync(thepath)){}。

我正在寻找这个问题的解决scheme,发现fs.exists和fs.existsSync已被弃用。 这似乎在我的senario中运行良好

 fs.readFile(filename, 'utf8', function(err,data){ // the err variable substitutes for the fs.exists callback function variable if (!err){ // do what you planned with the file console.log(data) }else{ // handle the non-existence of the file console.log('File does not exist!'); } }); 

没有必要使用fs.stat(),因为fs.existsSync()尚未被弃用。

https://nodejs.org/api/fs.html#fs_fs_existssync_path

fs.existsSync(path)

添加在:v0.1.21path| fs.exists()的同步版本。 如果文件存在则返回true,否则返回false。

请注意, fs.exists()已弃用,但fs.existsSync()不适用 。 (fs.exists()的callback>参数接受与其他> Node.jscallback不一致的参数。fs.existsSync()不使用callback。

你可以使用这个新的安装,并继续使用它:
https://github.com/imyller/node-fs-exists-nodeback

 npm install fs-exists-nodeback