mkdir-sync-recursive
Version:
Synchronously and recursively creates a directory. Returns undefined or the first directory path created.
74 lines (69 loc) • 1.89 kB
JavaScript
;
const node_fs = require('node:fs');
const node_path = require('node:path');
const validateUint32 = (value, name) => {
if (typeof value !== "number") {
throw new Error(`${name}: ${value} is not number`);
}
if (!Number.isInteger(value)) {
throw new Error(`${name}: ${value} is not an integer`);
}
const min = 0;
const max = 4294967295;
if (value < min || value > max) {
throw new Error(`${name}: ${value} must >= ${min} && <= ${max}`);
}
};
function parseFileMode(value, name, def) {
value ??= def;
if (typeof value === "string") {
if (!/^[0-7]+$/.test(value)) {
throw new Error(`${name}: ${value} is invalid`);
}
value = Number.parseInt(value, 8);
}
validateUint32(value, name);
return value;
}
function mkdirp(path, options) {
let mode = 511;
if (typeof options === "number" || typeof options === "string") {
mode = parseFileMode(options, "mode");
} else if (options?.mode) {
mode = parseFileMode(options.mode, "options.mode");
}
const _sep = path.includes("/") ? "/" : node_path.sep;
const dirs = path.split(_sep);
let dir = "";
const result = [];
for (const d of dirs) {
dir += `${d}${_sep}`;
mkdir(dir, mode);
}
function mkdir(path2, mode2) {
if (!node_fs.existsSync(dir)) {
try {
node_fs.mkdirSync(path2, mode2);
result.push(path2);
return true;
} catch {
return false;
}
}
return void 0;
}
return result.length ? node_path.resolve(result[0]) : void 0;
}
function mkdirSyncRecursive(path, options) {
let mpath;
if (typeof path === "string") {
mpath = mkdirp(path, options);
} else {
mpath = [];
for (const p of path) {
mpath.push(mkdirp(p, options));
}
}
return Array.isArray(mpath) ? mpath.some((m) => !!m) ? mpath : void 0 : mpath;
}
module.exports = mkdirSyncRecursive;