Making directory along with missing parents in Node.js

Note: By the time this post is written, the Node.js is on version 0.6.10. Therefore anything in this post may or may not valid in the newer versions.

Node.js file system API provide a bunch of functions to read/write files. One of them is the fs.mkdir(path, [mode], [callback]). However, this function itself does not provide any option for you to create a directory if the parents folder is missing, it’ll trigger an exception if you trying to do so. In another word, you can’t do something like “mkdir -p DIR”.

However, the callback function is an extreamly useful feature to extend this function. In case the fs.mkdir failed, it passes an error object into the callback function. Like this:

You’ll see it print an object looks like:

{ [Error: ENOENT, no such file or directory ‘parent/child’] errno: 34, code: ‘ENOENT’, path: ‘parent/child’ }

Good, now we know in the case of missing directory, we’ll get error code 34. What if we catch the error and try to recursively create it’s parent, then create the directory again? Everybody deserve a second chance, right?

Now you can run it like this;