25

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');
    }

};
3

2 Answers 2

55

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');
});

  
Sign up to request clarification or add additional context in comments.

Comments

1

Answer for post-2020 (v15 and up):

fs.statSync("some-file", { throwIfNoEntry: false })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.