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

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

    This version works better on Windows than the top answer because it understands both / and path.sep so that forward slashes work on Windows as they should. Supports absolute and relative paths (relative to the process.cwd).

    /**
     * Creates a folder and if necessary, parent folders also. Returns true
     * if any folders were created. Understands both '/' and path.sep as 
     * path separators. Doesn't try to create folders that already exist,
     * which could cause a permissions error. Gracefully handles the race 
     * condition if two processes are creating a folder. Throws on error.
     * @param targetDir Name of folder to create
     */
    export function mkdirSyncRecursive(targetDir) {
      if (!fs.existsSync(targetDir)) {
        for (var i = targetDir.length-2; i >= 0; i--) {
          if (targetDir.charAt(i) == '/' || targetDir.charAt(i) == path.sep) {
            mkdirSyncRecursive(targetDir.slice(0, i));
            break;
          }
        }
        try {
          fs.mkdirSync(targetDir);
          return true;
        } catch (err) {
          if (err.code !== 'EEXIST') throw err;
        }
      }
      return false;
    }
    

提交回复
热议问题