I have a JavaScript function that writes data to a .json file. Right now, whenever I run the function is deletes or overwrites the existing content on the .json file.
I want to change this so that whenever I run the function new data is appended to the file with the existing data remaining.
I've been reading about Node File System flags (eg flag: 'a'
) and have been trying to get this working but with no results (the old data is overwritten with the new. No errors occur).
My current function is:
function writeFile(obj) {
var jsonContent = JSON.stringify(obj, null, 2);
fs.writeFileSync("myData.json", jsonContent, 'utf8', { flag: 'as+' }, (err) => {
if (err) {
console.log("An error occurred while writing JSON Object to File.");
return console.log(err);
}
else {
console.log("File updated.");
}
});
}
I have also tried non synchronous:
fs.writeFile("myData.json", jsonContent, 'utf8', { flag: 'a+' }, (err) => {
and:
await fs.promises.writeFile("pagespeed.json", jsonContent, 'utf8', { flag: 'as+' }, (err) => {
But have gotten the same results (no errors, but overwrites not appends).
Would anyone know what I've done wrong or could point me in the right direction?