Code synchrone / bloquant
- const { readFileSync, writeFileSync } = require('fs')
- console.log('start')
- const first = readFileSync('./content/first.txt', 'utf8')
- const second = readFileSync('./content/second.txt', 'utf8')
- writeFileSync(
- './content/result-sync.txt',
- `Here is the result : ${first}, ${second}`,
- { flag: 'a' }
- )
- console.log('end')
- console.log('new')
Code asynchrone / non bloquant
- const { readFile, writeFile } = require('fs')
- console.log('start')
- readFile('./content/first.txt', 'utf8', (err, result) => {
- if (err) {
- console.log(err)
- return
- }
- const first = result
- readFile('./content/second.txt', 'utf8', (err, result) => {
- if (err) {
- console.log(err)
- return
- }
- const second = result
- writeFile(
- './content/result-async.txt',
- `Here is the result : ${first}, ${second}`,
- (err, result) => {
- if (err) {
- console.log(err)
- return
- }
- console.log('end')
- }
- )
- })
- })
- console.log('new')
Code asynchrone / non bloquant / promese
- const { readFile, writeFile } = require('fs').promises
- console.log('start');
- let result = "";
- readFile('./content/first.txt', 'utf8')
- .then((text) => {
- result = result.concat(text);
- return readFile('./content/second.txt', 'utf8')
- })
- .then((text) => {
- result = result.concat(text);
- writeFile('./content/promise.txt', `result: ${result}`, { flag: 'a' })
- })
- .then(() => console.log('end'))
- .catch((err) => console.log(err))
- console.log('new');
Code asynchrone / non bloquant / async
- const { readFile, writeFile } = require('fs').promises
- console.log('start');
- const start = async () => {
- try {
- const first = await readFile('./content/first.txt', 'utf8')
- const second = await readFile('./content/second.txt', 'utf8')
- await writeFile('./content/async.txt',`result : ${first} ${second}`,{ flag: 'a' })
- console.log('end');
- } catch (error) {
- console.log(error)
- }
- }
- start()
- 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');