Last active
October 31, 2020 00:35
-
-
Save bpedro/742162 to your computer and use it in GitHub Desktop.
nodejs implementation of recursive directory creation (https://brunopedro.com/2010/12/15/recursive-directory-nodejs/)
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'); | |
/** | |
* Offers functionality similar to mkdir -p | |
* | |
* Asynchronous operation. No arguments other than a possible exception | |
* are given to the completion callback. | |
*/ | |
function mkdir_p(path, mode, callback, position) { | |
mode = mode || 0777; | |
position = position || 0; | |
parts = require('path').normalize(path).split('/'); | |
if (position >= parts.length) { | |
if (callback) { | |
return callback(); | |
} else { | |
return true; | |
} | |
} | |
var directory = parts.slice(0, position + 1).join('/'); | |
fs.stat(directory, function(err) { | |
if (err === null) { | |
mkdir_p(path, mode, callback, position + 1); | |
} else { | |
fs.mkdir(directory, mode, function (err) { | |
if (err) { | |
if (callback) { | |
return callback(err); | |
} else { | |
throw err; | |
} | |
} else { | |
mkdir_p(path, mode, callback, position + 1); | |
} | |
}) | |
} | |
}) | |
} |
jaywcjlove
commented
Sep 17, 2015
another implementation using the latest fs
& path
function mkdir(dir) {
// we explicitly don't use `path.sep` to have it platform independent;
var sep = '/';
var segments = dir.split(sep);
var current = '';
var i = 0;
while (i < segments.length) {
current = current + sep + segments[i];
try {
fs.statSync(current);
} catch (e) {
fs.mkdirSync(current);
}
i++;
}
}
const path = require('path');
const fs = require('fs');
const mkdirp = dir => path
.resolve(dir)
.split(path.sep)
.reduce((acc, cur) => {
const currentPath = path.normalize(acc + path.sep + cur);
try {
fs.statSync(currentPath);
} catch (e) {
if (e.code === 'ENOENT') {
fs.mkdirSync(currentPath);
} else {
throw e;
}
}
return currentPath;
}, '');
const path = require("path");
const fs = require("fs");
function mkdirp(directory) {
if (!path.isAbsolute(directory)) return;
let parent = path.join(directory, "..");
if (parent !== path.join("/") && !fs.existsSync(parent)) mkdirp(parent);
if (!fs.existsSync(directory)) fs.mkdirSync(directory);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment