I am getting a little confused with what seems like nodes fs() various methods to check if a file exists.
I could : ( http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback )
fs.readFile('somefile.html', function (err, data) {
if (err) { /* it doesn't */ }
else { /* it does */ }
});
But that feels odd running the condition under an error ( it is expected that the file will not be there at times )
And then there is the fs.exists() ( http://nodejs.org/api/fs.html#fs_fs_exists_path_callback )
fs.exists('somefile.html', function (exists) {
if(exists) { /* it does */ }
else { /* it doesn't */ }
});
Which feels much more logical, but then I read this :
"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."
Which I understand, so before I go for the 'error way' -
What is the common way to check a file exists ( and if so open it ) / (perhaps quickest would be neat answer too) - using nodes fs()
?
Logic in my program is simply -
if (file does not exist) { continue the tasks to create it; }
else { read it and respond with it; }
Many Thanks