Getting error while trying to create new directory into my project folder

// Getting error throw new Error(`Error creating log folder ${logFolder} - 
// ${JSON.stringify(e)}`);
// Error: Error creating log folder ./logs/Pranjals-MacBook-Air.local -  
// {"errno":-2,"code":"ENOENT","syscall":"mkdir","path":"./logs/Pranjals- 
// MacBook-Air.local"}

// I am trying to create new directory if do not exists but it's throwing 
// me the error

let logFolder = `./logs/${os.hostname()}`;

if (!fs.existsSync(logFolder)) {
    try {
        fs.mkdirSync(logFolder);
    } catch(e) {
        throw new Error(`Error creating log folder ${logFolder} - ${JSON.stringify(e)}`);
    }
}

3 answers

  • answered 2018-11-08 08:21 Sparw

    To create directories recursively, I'm using mkdirp package.

    Here is an example :

    /**
     * CREATE DIR SYNC
     * Used to create a directory
     * @param {String} path
     */
    let createDirSync = function (path = '') {
        const fs = require('fs');
        const mkdirp = require('mkdirp');
        if (!fs.existsSync(path)) {
            mkdirp.sync(path);
        }
    };
    
    createDirSync('/path/to/create/');
    

    Hope it helps.

  • answered 2018-11-08 08:35 Nelson Owalo

    Compared to @Sparw's answer, you could do it without using a library. nodejs v10.x with the recursive option set to true.

    let logFolder = `./logs/${os.hostname()}`;
    
    if (!fs.existsSync(logFolder)) {
        try {
            await fs.promises.mkdir(logFolder, { recursive: true }) //or fs.mkdirSync(logFolder, { recursive: true })
        } catch(e) {
            throw new Error(`Error creating log folder ${logFolder} - ${JSON.stringify(e)}`);
        }
    }
    

  • answered 2018-11-08 11:42 Pranjal Sharma

    // I simply added '{recursive:true}' property as second parameter and it worked fine for me

    let logFolder = `logs/${os.hostname()}`;
    
    if (!fs.existsSync(logFolder)) {
        try {
           fs.mkdirSync(logFolder, { recursive: true })
        } catch(e) {
            throw new Error(`Error creating log folder ${logFolder} - ${JSON.stringify(e)}`);
        }
    }