I would like to send json updated on post response with express. Currently on my response the json is send but without to be updated.
Below function to edit json:
function editJSON(fr,en,es){
var obj = {
list_words: []
}
fs.readFile('./assets/words.json', 'utf-8', (err, jsonString) =>{
if(err){
console.log(err)
}else {
try{
obj = JSON.parse(jsonString)
obj.list_words.push({fr: fr, en: en, es: es})
json = JSON.stringify(obj)
fs.writeFile('./assets/words.json',JSON.stringify(null, 2),function (err){
console.log("test")
if (err) throw err;
console.log('complete');
})
} catch (err){
console.log(" Error parsing JSON", err)
}
}
})
}
and post request
const words = require('./assets/words.json')
app.post(
'/addwords',
(req,res)=>{
const errors = validationResult(req);
console.log(req.body)
const fr = req.body.fr
const en = req.body.en
const es = req.body.es
editJSON(fr,en,es)
console.log(words)
res.json(words) // old JSON is send
})