The mkdirpSync
function creates directories and their parents synchronously if they do not exist, and throws any other error if an issue occurs. It ignores the EEXISTS
error and throws others.
npm run import -- "mkdirp"
var fs = require('fs');
var path = require('path');
function mkdirpSync(p) {
if(!fs.existsSync(p)) {
try {
fs.mkdirSync(p);
} catch (e) {
if(e.code === 'ENOENT') {
mkdirpSync(path.dirname(p));
fs.mkdirSync(p);
} else if (e.code === 'EEXISTS') {
} else {
throw e
}
}
}
}
module.exports = mkdirpSync;
const fs = require('fs').promises;
const path = require('path');
/**
* Recursively creates a directory at the specified path.
*
* @param {string} dir - The path to the directory to be created.
* @returns {Promise} A promise that resolves when the directory is created.
*/
async function mkdirp(dir) {
if (!(await fs.exists(dir))) {
try {
// Attempt to create the directory
await fs.mkdir(dir, { recursive: true });
} catch (e) {
// If the directory does not exist, try to create its parent directory
if (e.code === 'ENOENT') {
// Recursively create the parent directory
await mkdirp(path.dirname(dir));
// Recursively create the target directory
await fs.mkdir(dir, { recursive: true });
} else if (e.code === 'EEXIST') {
// Handle the case where the directory already exists
// TODO: Log a warning or throw an error depending on the use case
} else {
// Re-throw any other errors
throw e;
}
}
}
}
// Export the function
module.exports = mkdirp;
mkdirpSync
A synchronous function that creates directories and their parents if they do not exist.
p
(string): The path to the directory to be created.ENOENT
: Thrown if a parent directory does not exist.EEXISTS
: Ignored if the directory already exists.