Skip to content

Instantly share code, notes, and snippets.

@kazemihabib
Forked from danherbert-epam/directory.js
Created August 20, 2016 15:43
Show Gist options
  • Save kazemihabib/35409c7e6b9beed3b41f48f6ed4383a0 to your computer and use it in GitHub Desktop.
Save kazemihabib/35409c7e6b9beed3b41f48f6ed4383a0 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