Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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?

like image 510
Calvin Froedge Avatar asked Feb 16 '15 00:02

Calvin Froedge


People also ask

How do I fix FS existsSync is not a function?

To use exist or existsSync , make sure you've imported fs using the sync API ( const fs = require("fs") ). Save this answer.

How do you check if a file exists using FS?

The easiest way to test if a file exists in the file system is by using the existsSync method. All you need to do is pass the path of the file to this method. The existsSync method will return true if the file exists and else it'll return false.


1 Answers

There is no need to use fs.stat(), because fs.existsSync() has not been deprecated.

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.)

like image 183
DDN-Shep Avatar answered Oct 24 '22 21:10

DDN-Shep