Je recommande vivement de ne pas utiliser les fonctions synchrones (bloquantes), car ils tiennent d'autres opérations simultanées . Au lieu de cela, utilisez la méthode asynchrone fs.promises :
const fs = require('fs').promises
const setValue = (fn, value) =>
fs.readFile(fn)
.then(body => JSON.parse(body))
.then(json => {
// manipulate your data here
json.value = value
return json
})
.then(json => JSON.stringify(json))
.then(body => fs.writeFile(fn, body))
.catch(error => console.warn(error))
Rappelez-vous que setValue
renvoie une promesse en attente, vous devrez utiliser la fonction Fonction .then ou, dans le cadre de fonctions asynchrones, la attendre l'opérateur .
// await operator
await setValue('temp.json', 1) // save "value": 1
await setValue('temp.json', 2) // then "value": 2
await setValue('temp.json', 3) // then "value": 3
// then-sequence
setValue('temp.json', 1) // save "value": 1
.then(() => setValue('temp.json', 2)) // then save "value": 2
.then(() => setValue('temp.json', 3)) // then save "value": 3