clr-dir
Version:
A npm package to organize the directory quickly
39 lines (31 loc) • 1.21 kB
JavaScript
/* https://stackoverflow.com/a/40686853 */
const fs = require("fs");
const path = require("path");
function mkDirByPathSync(targetDir, { isRelativeToScript = false } = {}) {
const sep = path.sep;
const initDir = path.isAbsolute(targetDir) ? sep : "";
const baseDir = isRelativeToScript ? __dirname : ".";
return targetDir.split(sep).reduce((parentDir, childDir) => {
const curDir = path.resolve(baseDir, parentDir, childDir);
try {
fs.mkdirSync(curDir);
console.log(curDir);
} catch (err) {
if (err.code === "EEXIST") {
// curDir already exists!
return curDir;
}
// To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
if (err.code === "ENOENT") {
// Throw the original parentDir error on curDir `ENOENT` failure.
throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`);
}
const caughtErr = ["EACCES", "EPERM", "EISDIR"].indexOf(err.code) > -1;
if (!caughtErr || (caughtErr && curDir === path.resolve(targetDir))) {
throw err; // Throw if it's just the last created dir.
}
}
return curDir;
}, initDir);
}
module.exports = mkDirByPathSync;