Skip to content

Instantly share code, notes, and snippets.

@danherbert-epam
Last active October 8, 2016 19:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save danherbert-epam/3960169 to your computer and use it in GitHub Desktop.
Save danherbert-epam/3960169 to your computer and use it in GitHub Desktop.
Cross-Platflorm node.js directory node module, which includes mkdir and mkdirSync utilities which behave like the UNIX command "mkdir -p" which can be given a path with lots of non-existent nested directories and create any that are missing. One thing missing here that could be added in the future is the optional 'mode' argument, which exists in…
var fs = require('fs');
var pathSep = require('path').sep;
var directory = module.exports = {};
directory.mkdirSync = function __directory_mkdirSync__(path) {
var dirs = path.split(pathSep);
var root = "";
while (dirs.length > 0) {
var dir = dirs.shift();
if (dir === "") {// If directory starts with a /, the first path will be an empty string.
root = pathSep;
}
if (!fs.existsSync(root + dir)) {
fs.mkdirSync(root + dir);
}
root += dir + pathSep;
}
};
module.exports.mkdir = function __directory_mkdir__(path, callback) {
var dirs = path.split(pathSep);
var root = "";
mkDir();
function mkDir(){
var dir = dirs.shift();
if (dir === "") {// If directory starts with a /, the first path will be an empty string.
root = pathSep;
}
fs.exists(root + dir, function(exists){
if (!exists){
fs.mkdir(root + dir, function(err){
root += dir + pathSep;
if (dirs.length > 0) {
mkDir();
} else if (callback) {
callback();
}
});
} else {
root += dir + pathSep;
if (dirs.length > 0) {
mkDir();
} else if (callback) {
callback();
}
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment