1

Is there anything like fs.create(path) that if path not exist then create it.

For example, fs.Create('D:/test/a.txt') and it will create test folder and a.txt file if a.txt not exist.

I know how to create the file if not exist but how about folder's'? I think it is a simple problem. Does any lib can do that? Or I need to parse the path and create it?

MichaelMao
  • 2,596
  • 2
  • 23
  • 54

2 Answers2

0

The answer is from @thefourtheye, Use fs-extra module's mkdirs

Lee
  • 29,398
  • 28
  • 117
  • 170
MichaelMao
  • 2,596
  • 2
  • 23
  • 54
0

If you don't want to add dependencies the following may work for you, where dirPath is an array of the path segments you want to mkdirsync to:

let dirPath = [cwd, `..`, `..`, `folderA`, `folderB`]
  let outDir = []
  dirPath.forEach(element => {
    outDir.push(element)
    try {
      if (!fs.existsSync(path.resolve(outDir.join('/')))) {
        fs.mkdirSync(path.resolve(outDir.join('/')))
        console.log('mkdir succeeded!!')
      }
    } catch (err) {
      console.error(err)
    }
  })