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

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

    You can simply check folder exist or not in path recursively and make the folder as you check if they are not present. (NO EXTERNAL LIBRARY)

    function checkAndCreateDestinationPath (fileDestination) {
        const dirPath = fileDestination.split('/');
        dirPath.forEach((element, index) => {
            if(!fs.existsSync(dirPath.slice(0, index + 1).join('/'))){
                fs.mkdirSync(dirPath.slice(0, index + 1).join('/')); 
            }
        });
    }
    

提交回复
热议问题