Async/sync

Code synchrone / bloquant 

  1. const { readFileSync, writeFileSync } = require('fs')
  2. console.log('start')
  3. const first = readFileSync('./content/first.txt', 'utf8')
  4. const second = readFileSync('./content/second.txt', 'utf8')

  5. writeFileSync(
  6.   './content/result-sync.txt',
  7.   `Here is the result : ${first}, ${second}`,
  8.   { flag: 'a' }
  9. )
  10. console.log('end')
  11. console.log('new')

Code asynchrone / non bloquant  

  1. const { readFile, writeFile } = require('fs')

  2. console.log('start')
  3. readFile('./content/first.txt', 'utf8', (err, result) => {
  4.   if (err) {
  5.     console.log(err)
  6.     return
  7.   }
  8.   const first = result
  9.   readFile('./content/second.txt', 'utf8', (err, result) => {
  10.     if (err) {
  11.       console.log(err)
  12.       return
  13.     }
  14.     const second = result
  15.     writeFile(
  16.       './content/result-async.txt',
  17.       `Here is the result : ${first}, ${second}`,
  18.       (err, result) => {
  19.         if (err) {
  20.           console.log(err)
  21.           return
  22.         }
  23.         console.log('end')
  24.       }
  25.     )
  26.   })
  27. })

  28. console.log('new')

Code asynchrone / non bloquant / promese


  1. const { readFile, writeFile } = require('fs').promises

  2. console.log('start');
  3. let result = "";
  4. readFile('./content/first.txt', 'utf8')
  5.   .then((text) => {
  6.     result = result.concat(text);
  7.     return readFile('./content/second.txt', 'utf8')
  8.   })
  9.   .then((text) => {
  10.     result = result.concat(text);
  11.     writeFile('./content/promise.txt', `result: ${result}`, { flag: 'a' })
  12.   })
  13.   .then(() => console.log('end'))
  14.   .catch((err) => console.log(err))
  15. console.log('new');


Code asynchrone / non bloquant / async

  1. const { readFile, writeFile } = require('fs').promises

  2. console.log('start');
  3. const start = async () => {
  4.   try {
  5.     const first = await readFile('./content/first.txt', 'utf8')
  6.     const second = await readFile('./content/second.txt', 'utf8')
  7.     await writeFile('./content/async.txt',`result : ${first} ${second}`,{ flag: 'a' })
  8.     console.log('end');
  9.   } catch (error) {
  10.     console.log(error)
  11.   }
  12. }

  13. start()
  14. console.log('new');

Notez le code exécuté en paralléle.

const { readFile, writeFile } = require('fs').promises

console.log('start');
const read1 = readFile('./content/first.txt', 'utf8')
const read2 = readFile('./content/second.txt', 'utf8')

Promise.all([read1, read2]).then((values) => {
  writeFile('./content/promise.txt', `result: ${values.join(" ")}`, { flag: 'a' })
  console.log('end');
});
console.log('new');