How to create a directory if it doesn't exist using Node.js?

前端 未结 18 1185
臣服心动
臣服心动 2020-11-30 16:03

Is this the right way to create a directory if it doesn\'t exist. It should have full permission for the script and readable by others.

var dir = __dirname +         


        
18条回答
  •  广开言路
    2020-11-30 16:48

    Here is a little function to recursivlely create directories:

    const createDir = (dir) => {
      // This will create a dir given a path such as './folder/subfolder' 
      const splitPath = dir.split('/');
      splitPath.reduce((path, subPath) => {
        let currentPath;
        if(subPath != '.'){
          currentPath = path + '/' + subPath;
          if (!fs.existsSync(currentPath)){
            fs.mkdirSync(currentPath);
          }
        }
        else{
          currentPath = subPath;
        }
        return currentPath
      }, '')
    }
    

提交回复
热议问题