0

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

Rob Sedgwick
  • 5,216
  • 4
  • 20
  • 36

1 Answers1

3

You can use readFileSync to do sort of what you want

var file = fs.readFileSync('somefile.html');
if (file) { do stuff }
else { error }

The moral of the story is you don't need to do exists. That is purely a check to see if the file exists. You can just run readFile if it can't open it, it will error. If it can it will return the data.

Steven
  • 13,250
  • 33
  • 95
  • 147
  • hmm, gotya. - I would prefer the async version of this method - should work the same way though right ? – Rob Sedgwick Feb 16 '14 at 18:27
  • and so between fs.open and fs.readfile -- you would choose fs.readfile ( async or sync ) any reason why ? sorry to bother .. – Rob Sedgwick Feb 16 '14 at 18:28
  • You can read more about sync vs async at http://stackoverflow.com/questions/13858909/synchronous-vs-asynchronous-code-with-node-js they work the exact same, except for the way the callback/function/value get's run/set. – Steven Feb 16 '14 at 18:29
  • The moral of the story is you don't need to do exists. That is purely a check to see if the file exists. You can just run `readFile` if it can't open it, it will error. If it can it will return the data. – Steven Feb 16 '14 at 18:32
  • Yeah man, that's what Im finding on my travels - would you mind popping that comment line into your answer ? and I'll accept. Thanks. – Rob Sedgwick Feb 16 '14 at 18:35
  • Thanks again @Steven - just needed that bit of reassurance with using this method ( it will get hammered ) – Rob Sedgwick Feb 16 '14 at 18:38