await-no-overwrite.js 833 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const fs = require('fs').promises

// Creates an array of files. If any file already exists,
// no files are created and an error is thrown.
async function writeFiles(files) {
  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    try {
      // Write to the file, but throw an error if the file exists
      await fs.writeFile(file.name, file.contents, {flag: 'wx'})
    }
    catch (e) {
      // File already exists, so remove all the previously created files
      await Promise.all(files.slice(0, i).map(file =>
        fs.unlink(file.name)
      ))
      // Re-throw the error
      throw e
    }
  }
}

// Try to create 3 files
writeFiles([
  {name: 'a.txt', contents: 'abc'},
  {name: 'b.txt', contents: '123'},
  {name: 'c.txt', contents: 'xyz'}
])
  .catch(_ => console.log('Some files already existed'))