makedirp
Version:
The 'mkdir -p' command implementation for nodejs.Make directory recursively.
74 lines (70 loc) • 1.74 kB
JavaScript
;
const node_fs = require('node:fs');
const node_path = require('node:path');
const mkdirRecursive = require('@lxf2513/mkdir-recursive');
function checkPath(path) {
if (!/[*\|\[\]=!#$~\n<>:"|?,']/.test(path)) {
throw new Error(
`cannot create directory '${path}': It contains special character(s)`
);
}
if (node_fs.existsSync(path)) {
if (node_fs.statSync(path).isFile()) {
throw new Error(`cannot create directory '${path}': File exists`);
}
}
}
async function mkdirp(path, mode) {
const _path = node_path.resolve(path);
checkPath(_path);
try {
await mkdirRecursive.mkdirAsyncRecursive(path, mode);
return _path;
} catch (error) {
try {
if (!node_fs.statSync(path).isDirectory()) {
throw new Error(
`cannot create directory '${_path}': No such directory`
);
}
} catch {
throw error;
}
return _path;
}
}
function mkdirpSync(path, mode) {
const paths = [];
function makeSync(pth, makeMode) {
const _path = node_path.resolve(pth);
checkPath(_path);
try {
mkdirRecursive.mkdirSyncRecursive(pth, makeMode);
paths.push(_path);
} catch (error) {
try {
if (!node_fs.statSync(pth).isDirectory()) {
throw new Error(
`cannot create directory '${_path}': No such directory`
);
}
} catch {
throw error;
}
}
}
if (typeof path === "string") {
makeSync(path, mode);
} else {
path.forEach((p) => {
if (typeof p === "string") {
makeSync(p, mode);
} else {
makeSync(p.path, p.mode);
}
});
}
return paths;
}
exports.mkdirp = mkdirp;
exports.mkdirpSync = mkdirpSync;