Skip to content

Instantly share code, notes, and snippets.

@aelaguiz
Created March 10, 2011 16:58
Show Gist options
  • Save aelaguiz/864454 to your computer and use it in GitHub Desktop.
Save aelaguiz/864454 to your computer and use it in GitHub Desktop.
node.js function to create full directory path (like mkdir -p)
exports.createFullPath = function createFullPath(fullPath, callback) {
var parts = path.dirname(path.normalize(fullPath)).split("/"),
working = '/',
pathList = [];
for(var i = 0, max = parts.length; i < max; i++) {
working = path.join(working, parts[i]);
pathList.push(working);
}
var recursePathList = function recursePathList(paths) {
if(0 === paths.length) {
callback(null);
return ;
}
var working = paths.shift();
try {
path.exists(working, function(exists) {
if(!exists) {
try {
fs.mkdir(working, 0755, function() {
recursePathList(paths);
});
}
catch(e) {
callback(new Error("Failed to create path: " + working + " with " + e.toString()));
}
}
else {
recursePathList(paths);
}
});
}
catch(e) {
callback(new Error("Invalid path specified: " + working));
}
}
if(0 === pathList.length)
callback(new Error("Path list was empty"));
else
recursePathList(pathList);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment