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

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

    You can just use mkdir and catch the error if the folder exists.
    This is async (so best practice) and safe.

    fs.mkdir('/path', err => { 
        if (err && err.code != 'EEXIST') throw 'up'
        .. safely do your stuff here  
        })
    

    (Optionally add a second argument with the mode.)


    Other thoughts:

    1. You could use then or await by using native promisify.

      const util = require('util'), fs = require('fs');
      const mkdir = util.promisify(fs.mkdir);
      var myFunc = () => { ..do something.. } 
      
      mkdir('/path')
          .then(myFunc)
          .catch(err => { if (err.code != 'EEXIST') throw err; myFunc() })
      
    2. You can make your own promise method, something like (untested):

      let mkdirAsync = (path, mode) => new Promise(
         (resolve, reject) => mkdir (path, mode, 
            err => (err && err.code !== 'EEXIST') ? reject(err) : resolve()
            )
         )
      
    3. For synchronous checking, you can use:

      fs.existsSync(path) || fs.mkdirSync(path)
      
    4. Or you can use a library, the two most popular being

      • mkdirp (just does folders)
      • fsextra (supersets fs, adds lots of useful stuff)

提交回复
热议问题