---
title: "Recursive directory creation with nodejs"
date: 2010-12-15
description: "I’m doing some code in nodejs and I found the need to create directories recursively. Basically I need to have the same functionality offered by mkdir -p.\nThe fs lib doesn’t offer this functionality …"
---


I'm doing some code in [nodejs][1] and I found the need to create directories recursively. Basically I need to have the same functionality offered by mkdir -p.

The [fs][2] lib doesn't offer this functionality so I looked around but couldn't really find anything that suited me. I finally gave up and I'm writing the function myself.

Here's [the code][3]:

{{< highlight javascript "linenos=table" >}}
var fs = require('fs');

/**
 * Offers functionality similar to mkdir -p
 *
 * Asynchronous operation. No arguments other than a possible exception
 * are given to the completion callback.
 */
function mkdir_p(path, mode, callback, position) {
    mode = mode || 0777;
    position = position || 0;
    parts = require('path').normalize(path).split('/');

    if (position >= parts.length) {
        if (callback) {
            return callback();
        } else {
            return true;
        }
    }

    var directory = parts.slice(0, position + 1).join('/');
    fs.stat(directory, function(err) {
        if (err === null) {
            mkdir_p(path, mode, callback, position + 1);
        } else {
            fs.mkdir(directory, mode, function (err) {
                if (err) {
                    if (callback) {
                        return callback(err);
                    } else {
                        throw err;
                    }
                } else {
                    mkdir_p(path, mode, callback, position + 1);
                }
            })
        }
    })
}
{{< /highlight >}}

**Update**: I just converted this code into an extension to the original fs lib so that it's easier to use. The extended lib is called [node-fs][4] and is [available on `npm`][5]. To install it, simply run `npm install node-fs --save`.

[1]: http://nodejs.org
[2]: http://nodejs.org/docs/v0.3.1/api/fs.html
[3]: https://gist.github.com/bpedro/742162
[4]: https://github.com/bpedro/node-fs
[5]: https://www.npmjs.com/package/node-fs
