Calvin Froedge Calvin Froedge - 1 month ago 25
Node.js Question

fs.exists, fs.existsSync - why are they deprecated?

I noticed that the official node documentation says something startling about 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."


I understand the suggestion, to open a file and then handle the error if it doesn't exist, but what I don't understand is why the interface is being deprecated rather than the implementation simply changing.

Can anyone explain to me why checking for the existence of a file with an api that is as simple and logical as fs.exists is such a bad thing that it should be called an anti-pattern and removed from the node API?

Answer

I think it because it's redundant. You can check if a file exists by trying to open it. It will give you ENOENT if it doesn't exist:

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