mkdir-sync-recursive
Version:
Synchronously and recursively creates a directory. Returns undefined or the first directory path created.
72 lines (68 loc) • 1.86 kB
JavaScript
import { existsSync, mkdirSync } from 'node:fs';
import { sep, resolve } from '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("/") ? "/" : 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 (!existsSync(dir)) {
try {
mkdirSync(path2, mode2);
result.push(path2);
return true;
} catch {
return false;
}
}
return void 0;
}
return result.length ? 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;
}
export { mkdirSyncRecursive as default };