I was looking for a way to check if a directory exists and if not, create it. My first try was with the file system module's "exists" method - https://nodejs.org/api/fs.html#fsfsexistspathcallback. The problem with this method is that it is deprecated! Makes no sense using it.
The hint was to use the fs.stat method. This function returns (surprise) the stats of a file system object - whether a directory or a file. What the documentation failed to mention was - what happened when the file or directory doesn't exist! It only says

The callback gets two arguments (err, stats) where stats is a fs.Stats object.

Wonderful.
Surprisingly (or not :) ), fs.stat's callback will return an error, if the file doesn't exist. So with the async method, one might do something like this (assuming fs is already defined, of course):

//function will check if a directory exists, and create it if it doesn't
function checkDirectory(directory, callback) {  
  fs.stat(directory, function(err, stats) {
    //Check if error defined and the error code is "not exists"
    if (err && err.errno === 34) {
      //Create the directory, call the callback.
      fs.mkdir(directory, callback);
    } else {
      //just in case there was a different error:
      callback(err)
    }
  });
}

Usage is rather simple:

checkDirectory("./logs/", function(error) {  
  if(error) {
    console.log("oh no!!!", error);
  } else {
    //Carry on, all good, directory exists / created.
  }
});

This works async. Sadly, I had to use the sync method. The Sync methods don't have any way of notifying about an error. Except for exceptions! As it turns out, the fs.statSync method throws an exception when the file or directory doesn't exist. Creating the sync version is as easy as that:

function checkDirectorySync(directory) {  
  try {
    fs.statSync(directory);
  } catch(e) {
    fs.mkdirSync(directory);
  }
}

And that's it.
Using is as simple as before:

checkDirectorySync("./logs");  
//directory created / exists, all good.

Of course, you should handle the (unexpected) exception of problems while creating the directory, just like with any Sync method used.

And that's it. Rather easy and self explanatory. Just thought someone else might find it useful.

Connect with me on Twitter or LinkedIn to continue the discussion.

I'm an IT consultant, full stack developer, husband, and father. On my spare time I am contributing to Babylon.js WebGL game engine and other open source projects.

Berlin, Germany