Node.js create folder or use existing

后端 未结 14 1464
暖寄归人
暖寄归人 2020-12-04 06:43

I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdi

14条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 07:31

    You can do all of this with the File System module.

    const
      fs = require('fs'),
      dirPath = `path/to/dir`
    
    // Check if directory exists.
    fs.access(dirPath, fs.constants.F_OK, (err)=>{
      if (err){
        // Create directory if directory does not exist.
        fs.mkdir(dirPath, {recursive:true}, (err)=>{
          if (err) console.log(`Error creating directory: ${err}`)
          else console.log('Directory created successfully.')
        })
      }
      // Directory now exists.
    })
    

    You really don't even need to check if the directory exists. The following code also guarantees that the directory either already exists or is created.

    const
      fs = require('fs'),
      dirPath = `path/to/dir`
    
    // Create directory if directory does not exist.
    fs.mkdir(dirPath, {recursive:true}, (err)=>{
      if (err) console.log(`Error creating directory: ${err}`)
      // Directory now exists.
    })
    

提交回复
热议问题