Created
January 11, 2013 15:57
-
-
Save kaizhu256/4511752 to your computer and use it in GitHub Desktop.
nodejs - asynchronously and recursively create nested directories (like mkdir -p) in under 50 lines of code
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
/*jslint bitwise: true, indent: 2, nomen: true, regexp: true, stupid: true*/ | |
(function () { | |
'use strict'; | |
exports.requireFs = require('fs'); | |
exports.requirePath = require('path'); | |
function _fsMkdirP(dirname, callback) { | |
exports.requireFs.mkdir(dirname, function (err) { | |
switch (err && err.code) { | |
case 'ENOENT': | |
_fsMkdirP(exports.requirePath.dirname(dirname), function (err) { | |
if (err) { | |
callback(err); | |
return; | |
} | |
exports.requireFs.mkdir(dirname, callback); | |
}); | |
return; | |
case 'EEXIST': | |
callback(); | |
return; | |
default: | |
callback(err); | |
} | |
}); | |
} | |
exports.fsMkdirP = function (dirname, callback) { | |
_fsMkdirP(dirname, callback || function () {}); | |
}; | |
//// test | |
exports.fsMkdirP('/tmp/a/b/c/d/e', function (err) { | |
if (err) { | |
console.error(err.stack); | |
return; | |
} | |
console.log('finished asynchronously creating directory /tmp/a/b/c/d/e'); | |
}); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment