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

后端 未结 22 1867
故里飘歌
故里飘歌 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:37

    Here's my imperative version of mkdirp for nodejs.

    function mkdirSyncP(location) {
        let normalizedPath = path.normalize(location);
        let parsedPathObj = path.parse(normalizedPath);
        let curDir = parsedPathObj.root;
        let folders = parsedPathObj.dir.split(path.sep);
        folders.push(parsedPathObj.base);
        for(let part of folders) {
            curDir = path.join(curDir, part);
            if (!fs.existsSync(curDir)) {
                fs.mkdirSync(curDir);
            }
        }
    }
    

提交回复
热议问题