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?
To use exist or existsSync , make sure you've imported fs using the sync API ( const fs = require("fs") ). Save this answer.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With