I have a problem writing a json file using creatwritestream NodeJS. The JSON in file is ok But it append in the file, I need overwrite the content. I storing selected answer when clicked on button.
Example: Question A : Evaluated selected : D ANSWER (Save this in json) Question B: Evaluated selected : C ANSWER (Save this in json)
I GOT:
{"IdTest":"1021","answers":[{"questionID":"1","answerSelected":"D"}]}\n {"IdTest":"1021","answers":[{"questionID":"1","answerSelected":"D"},{"questionID":"2","answerSelected":"C"}]}
This is my code:
//init variables
let jsonObject = {};
const JSON_ANSWERS_FILE = fs.createWriteStream("path/to/jsons/file.json", {
flags: 'w',
encoding: 'utf8'
});
//I created the key and value for the json object
jsonObject = {
"id": 123,
"answers": []
}
// BUTTON TO SAVE ANSWER IN JSON
jsonObject.answers.push({
"qID": $("#element").text(),
"selected": $("input:radio[name=radioName]:checked").attr("value")
})
JSON_ANSWERS_FILE.write(JSON.stringify(jsonObject), (error) => {
if (error) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'message'
})
}
})