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

前端 未结 18 1125
臣服心动
臣服心动 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 17:01

    With Node 10 + ES6:

    import path from 'path';
    import fs from 'fs';
    
    (async () => {
      const dir = path.join(__dirname, 'upload');
    
      try {
        await fs.promises.mkdir(dir);
      } catch (error) {
        if (error.code === 'EEXIST') {
          // Something already exists, but is it a file or directory?
          const lstat = await fs.promises.lstat(dir);
    
          if (!lstat.isDirectory()) {
            throw error;
          }
        } else {
          throw error;
        }
      }
    })();
    

提交回复
热议问题