copy-promises.js 661 Bytes
/*
  Note the `.promises`.
  `require('fs').promises` has the same functions as `require('fs')`,
  but they return Promises instead of taking callbacks.
*/
const fs = require('fs').promises

// Read 'a.txt'. `readPromise` is a `Promise<string>`.
const readPromise = fs.readFile('a.txt', 'utf8')
/*
  After `readPromise` finishes, write the result to 'b.txt'.
  `contents` will be the `string` that was read.
  We return a `Promise<undefined>` that represents the write.
*/
const writePromise = readPromise
  .then(contents => fs.writeFile('b.txt', contents))
// Once the write finishes, print a message
writePromise.then(_ => {
  console.log('Copying done')
})