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

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

    fs.exist() is deprecated. So I have used fs.stat() to check the directory status. If the directory does not exist fs.stat() throw an error with message like 'no such file or directory'. Then I have created a directory.

    const fs = require('fs').promises;
        
    const dir = './dir';
    fs.stat(dir).catch(async (err) => {
      if (err.message.includes('no such file or directory')) {
        await fs.mkdir(dir);
      }
    });
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-30 16:55

    I had to create sub-directories if they didn't exist. I used this:

    const path = require('path');
    const fs = require('fs');
    
    function ensureDirectoryExists(p) {
        //console.log(ensureDirectoryExists.name, {p});
        const d = path.dirname(p);
        if (d && d !== p) {
            ensureDirectoryExists(d);
        }
        if (!fs.existsSync(d)) {
            fs.mkdirSync(d);
        }
    }
    
    0 讨论(0)
  • 2020-11-30 17:00

    With the fs-extra package you can do this with a one-liner:

    const fs = require('fs-extra');
    
    const dir = '/tmp/this/path/does/not/exist';
    fs.ensureDirSync(dir);
    
    0 讨论(0)
  • 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;
        }
      }
    })();
    
    0 讨论(0)
  • 2020-11-30 17:02

    The best solution would be to use the npm module called node-fs-extra. It has a method called mkdir which creates the directory you mentioned. If you give a long directory path, it will create the parent folders automatically. The module is a super set of npm module fs, so you can use all the functions in fs also if you add this module.

    0 讨论(0)
提交回复
热议问题