fs.statSync throws error if file does not exist

I am attempting to determine if a file exists. If it does not exist, I would like my code to continue so it will be created. When I use the following code, if the file exists, it prints that 'it exists'. If it does not exist, it crashes my app. Here is my code:

var checkDuplicateFile = function(){
    var number = room.number.toString();
    var stats = fs.statSync(number);
    if(stat){
        console.log('it exists');
    }else{
        console.log('it does not exist');
    }

};

Solution 1:

Your application is crashing because you're not wrapping your fs.statSync in a try/catch block. Sync functions in node don't return the error like they would in their async versions. Instead, they throw their errors which need to be caught.

try {
  var stats = fs.statSync(number);
  console.log('it exists');
}
catch(err) {
    console.log('it does not exist');
}

If your app doesn't require this operation to be synchronous (block further execution until this operation is finished) then I would use the async version.

fs.stat(number, function(err, data) {
  if (err) 
    console.log('it does not exist');
  else 
    console.log('it exists');
});