Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js best practice check for file exists

Tags:

node.js

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
    }
}
like image 330
Klaasvaak Avatar asked Oct 20 '22 10:10

Klaasvaak


1 Answers

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.

like image 181
Brad Avatar answered Nov 03 '22 01:11

Brad