How to create full path with node's fs.mkdirSync?

后端 未结 22 1868
故里飘歌
故里飘歌 2020-11-29 18:03

I\'m trying to create a full path if it doesn\'t exist.

The code looks like this:

var fs = require(\'fs\');
if (!fs.existsSync(newDest)) fs.mkdirSync         


        
22条回答
  •  一整个雨季
    2020-11-29 18:20

    Based on mouneer's zero-dependencies answer, here's a slightly more beginner friendly Typescript variant, as a module:

    import * as fs from 'fs';
    import * as path from 'path';
    
    /**
    * Recursively creates directories until `targetDir` is valid.
    * @param targetDir target directory path to be created recursively.
    * @param isRelative is the provided `targetDir` a relative path?
    */
    export function mkdirRecursiveSync(targetDir: string, isRelative = false) {
        const sep = path.sep;
        const initDir = path.isAbsolute(targetDir) ? sep : '';
        const baseDir = isRelative ? __dirname : '.';
    
        targetDir.split(sep).reduce((prevDirPath, dirToCreate) => {
            const curDirPathToCreate = path.resolve(baseDir, prevDirPath, dirToCreate);
            try {
                fs.mkdirSync(curDirPathToCreate);
            } catch (err) {
                if (err.code !== 'EEXIST') {
                    throw err;
                }
                // caught EEXIST error if curDirPathToCreate already existed (not a problem for us).
            }
    
            return curDirPathToCreate; // becomes prevDirPath on next call to reduce
        }, initDir);
    }
    

提交回复
热议问题