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

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

    I solved the problem this way - similar to other recursive answers but to me this is much easier to understand and read.

    const path = require('path');
    const fs = require('fs');
    
    function mkdirRecurse(inputPath) {
      if (fs.existsSync(inputPath)) {
        return;
      }
      const basePath = path.dirname(inputPath);
      if (fs.existsSync(basePath)) {
        fs.mkdirSync(inputPath);
      }
      mkdirRecurse(basePath);
    }
    

提交回复
热议问题