Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

};
like image 284
Mike Avatar asked Oct 28 '15 19:10

Mike


1 Answers

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

  
like image 173
peteb Avatar answered Oct 16 '22 02:10

peteb