Skip to content

Instantly share code, notes, and snippets.

@aseemk
Created June 29, 2011 08:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aseemk/1053383 to your computer and use it in GitHub Desktop.
Save aseemk/1053383 to your computer and use it in GitHub Desktop.
My implementation of a synchronous `mkdir -p` for Node.
# synchronously creates the directory at the given path, including all
# intermediate directories, if it doesn't already exist. (like `mkdir -p`)
mkdirpSync = (dir) ->
# normalize and resolve path to an absolute one:
# (path.resolve automatically uses the current directory if needed)
dir = path.resolve path.normalize dir
# try to create this directory:
try
# XXX hardcoding recommended file mode of 511 (0777 in octal)
# (note that octal numbers are disallowed in ES5 strict mode)
fs.mkdirSync dir, 511
# and if we fail, base action based on why we failed:
catch e
switch e.errno
# base case: if the path already exists, we're good to go.
# TODO account for this path being a file, not a dir?
when constants.EEXIST
return
# recursive case: some directory in the path doesn't exist, so
# make this path's parent directory.
when constants.ENOENT
mkdirpSync path.dirname dir
mkdirpSync dir
else
throw e
@winse
Copy link

winse commented Feb 25, 2014

I think that may be better...

var fs = require("fs");
var path = require("path");

var mkdirs = function (fold, callback) {

    var pf = path.dirname(fold);
    fs.exists(pf, function (exists) {
        var create = function () {
            fs.mkdir(fold, callback);
        }

        if (exists) {
            create();
        } else
            mkdirs(pf, create);
    })

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment