Projects/Superalgos/TS/Utilities/MiscellaneousFunctions.js
/* Function to create folders of missing folders at any path. */
Function to create folders of missing folders at any path.
Function to create folders of missing folders at any path .
function mkDirByPathSync(targetDir, { isRelativeToScript = false } = {}) {
        const path = require('path')
        targetDir = targetDir.substring(0, targetDir.lastIndexOf('/') + 1);
        const sep = '/';
        const initDir = path.isAbsolute(targetDir) ? sep : '';
        const baseDir = isRelativeToScript ? __dirname : '.';
        return targetDir.split(sep).reduce((parentDir, childDir) => {
            const curDir = path.resolve(baseDir, parentDir, childDir);
            try {
                const fs = require('fs')
                fs.mkdirSync(curDir);
            } catch (err) {
                if (err.code === 'EEXIST') { 
                    return curDir;
                }
                if (err.code === 'ENOENT') { 
                    throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`);
                }
                const caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1;
                if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
                    throw err; 
                }
            }
            return curDir;
        }, initDir);
    }
function mkDirByPathSync ( targetDir , { isRelativeToScript = false } = { } ) { const path = require ( 'path' ) targetDir = targetDir . substring ( 0 , targetDir . lastIndexOf ( '/' ) + 1 ) ; const sep = '/' ; const initDir = path . isAbsolute ( targetDir ) ? sep : '' ; const baseDir = isRelativeToScript ? __dirname : '.' ; return targetDir . split ( sep ) . reduce ( ( parentDir , childDir ) => { const curDir = path . resolve ( baseDir , parentDir , childDir ) ; try { const fs = require ( 'fs' ) fs . mkdirSync ( curDir ) ; } catch ( err ) { if ( err . code === 'EEXIST' ) { return curDir ; } if ( err . code === 'ENOENT' ) { throw new Error ( ` ${ parentDir } ` ) ; } const caughtErr = [ 'EACCES' , 'EPERM' , 'EISDIR' ] . indexOf ( err . code ) > - 1 ; if ( ! caughtErr || caughtErr && curDir === path . resolve ( targetDir ) ) { throw err ; } } return curDir ; } , initDir ) ; }
Function to create folders of missing folders at any path.
Function to create folders of missing folders at any path .
// curDir already exists! // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows. // Throw the original parentDir error on curDir `ENOENT` failure. // Throw if it's just the last created dir.