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

前端 未结 18 1165
臣服心动
臣服心动 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:52

    Using async / await:

    const mkdirP = async (directory) => {
      try {
        return await fs.mkdirAsync(directory);
      } catch (error) {
        if (error.code != 'EEXIST') {
          throw e;
        }
      }
    };
    

    You will need to promisify fs:

    import nodeFs from 'fs';
    import bluebird from 'bluebird';
    
    const fs = bluebird.promisifyAll(nodeFs);
    

提交回复
热议问题