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

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

    Exec can be messy on windows. There is a more "nodie" solution. Fundamentally, you have a recursive call to see if a directory exists and dive into the child (if it does exist) or create it. Here is a function that will create the children and call a function when finished:

    fs = require('fs');
    makedirs = function(path, func) {
     var pth = path.replace(/['\\]+/g, '/');
     var els = pth.split('/');
     var all = "";
     (function insertOne() {
       var el = els.splice(0, 1)[0];
       if (!fs.existsSync(all + el)) {
        fs.mkdirSync(all + el);
       }
       all += el + "/";
       if (els.length == 0) {
        func();
       } else {
         insertOne();
       }
       })();
    

    }

提交回复
热议问题