Reputation: 5644
What is the best practise to check if a file exists with Node.js?
In other questions on here I see alot of answers saying to use fs.exists
But the docs say:
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.
What happends when you open a file? Does it stay open untill you close it (is this a leak?)? So, do you have to close the file after you opened it? And if I use fs.exists
do I open the file too?
Does this mean the best way to check if a file exists is:
fs.open('path/file.js', function(err, fd) {
if (err && err.code == 'ENOENT') {
// Does not exist
} else if (!err) {
// Does exist
fs.close(fd);
} else {
// Some other error
}
}
Upvotes: 5
Views: 2791
Reputation: 163232
What happends when you open a file? Does it stay open untill you close it (is this a leak?)?
Yes, if you open a file you must close it. Otherwise it will remain open until your process dies.
And if I use fs.exists do I open the file too?
Simply calling fs.exists()
does not open the file, so there is nothing to close.
If you have a reason for only checking to see if a file exists, you should use fs.exists()
. The documentation is saying that if what you really want to do is open a file, there is no need to check fs.exists()
beforehand. If you want to open a file, just try to open it and handle the errors.
Upvotes: 3