files | file tools, match filename | changing file names | Search

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.

Run example

npm run import -- "mkdirp"

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;

What the code could have been:

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;

Function: mkdirpSync

Description

A synchronous function that creates directories and their parents if they do not exist.

Parameters

Behavior

Exceptions