14

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

3
  • Check your err first. It's very likely you have encountered an error if stats is undefined.
    – Oka
    Mar 7, 2016 at 16:57
  • 1. You should check for errors first. 2. If it doesn't exist, stats is undefined
    – baao
    Mar 7, 2016 at 16:58
  • Apologies, I've just realised that as I hit submit, so I have edited my question
    – K20GH
    Mar 7, 2016 at 16:59

2 Answers 2

32

Check err first. Then check isDirectory()

fs.stat("temp/" + seriesid, function (err, stats){
  if (err) {
    // Directory doesn't exist or something.
    console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
    return fs.mkdir("temp/" + seriesid, callback);
  }
  if (!stats.isDirectory()) {
    // This isn't a directory!
    callback(new Error('temp is not a directory!'));
  } else {
    console.log('Does exist');
    callback();
  }
});
1
0

you need to check if stats exist before doing !stats.isDirectory()

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.