Last active
August 29, 2015 13:56
-
-
Save tomgidden/8967494 to your computer and use it in GitHub Desktop.
node.js mkdirp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
function mkdirp(fn, perms, cb) | |
// Make a directory and its ancestors if necessary. | |
{ | |
// 'perms' is optional, but callback is the last param | |
if(arguments.length === 2) { | |
cb = arguments[arguments.length-1]; | |
perms = 0x1fd/*0775*/; | |
} | |
// To expose a nice interface, we wrap the recursive function itself. | |
var _mkdirp = function (e, fn, cb2) { | |
// We ignore EEXIST. Lame. | |
if(e && e.code !== 'EEXIST') throw e; | |
// Create directory recursively, blithely ignoring errors on the way. | |
// We start at the leaf (not the root) of the tree, eg. 'a/b/c/d'. | |
// So, check if it's a path (eg. 'a/b/c'), or if we're at the root (eg. 'a') | |
if(fn.indexOf('/') === -1) { | |
// We're at the root of the tree, so we can now start building | |
// folders and collapting the tree. | |
fs.mkdir(fn, perms, cb2); | |
} | |
else { | |
// It's a path, so recurse: start at a higher level. We want | |
// to build a recursion tree with each tail creating the next | |
// subfolder. When we've constructed it all, the recursion | |
// will collapse, starting with a mkdir of the root folder. | |
// Head recursion rocks... honest. | |
_mkdirp(null, | |
path.dirname(fn), | |
function (e) { | |
// We ignore EEXIST. Lame. | |
if(e && e.code !== 'EEXIST') throw e; | |
// Okay, we're now collapsing the recursion, so | |
// make the directory and pass to the next mkdir | |
// (the child folder, but the parent function | |
// call!) | |
fs.mkdir(fn, perms, cb2); | |
}); | |
} | |
}; | |
// Okay, start the recursion. | |
_mkdirp(null, fn, function (e) { | |
// We ignore EEXIST. Lame. | |
if(e && e.code !== 'EEXIST') throw e; | |
e = null; | |
cb(e); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment