Node - Check to see if a directory exists

Viewed 14504

This should be a fairly simple one to answer I would hope, however it's got me stumped - maybe I've been staring at too much code today!

I am trying to do a simple if statement which checks to see if a folder exists. If the folder doesn't exist, make it, if it does, delete the content.

The problem I am having is that if the directory doesn't exist, then the callback (stats) is undefined. With fs.exist it would be quite simple, but since its deprecated, I wanted to ensure this was future proofed.

var seriesid = 5;
      fs.stat("temp/" + seriesid, function (err, stats){
        if(!stats.isDirectory()){
          fs.mkdir("temp/" + seriesid);
          console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
          callback();
        }
        else if (err != 'ENOENT') {
          callback(err);
        }
        else {
          // TODO: Folder exists, delete contents
          console.log('Does exist');
          callback();
        }
      });

Any help on how to accomplish this would be appreciated

2 Answers
Related