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'))
-
Caleb C. Sander authoredecfb12b9