Calvin Froedge Calvin Froedge - 9 days ago 8x
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 Just open the file and handle the error when it's not

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?


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:

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