2

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?

MeltingDog
  • 14,310
  • 43
  • 165
  • 295
  • 1
    Use [appendFile](https://nodejs.org/api/fs.html#fsappendfilesyncpath-data-options) for append. BUT appending doesn't make sense for json. Multiple root objects in a json file is not valid json. – Ricky Mo Jul 19 '23 at 06:11

1 Answers1

2

You are passing in too many arguments into fs.writeFileSync and fs.writeFile.

Instead of doing

fs.writeFile("myData.json", jsonContent, 'utf8', { flag: 'as+' }, (err) => { .... });

fs.writeFileSync("myData.json", jsonContent, 'utf8', { flag: 'as+' }, (err) => { .... });

do this:

const result = fs.writeFileSync("myData.json", jsonContent, { encoding:'utf8', flag: 'as+' });

// OR

const result = await fs.writeFile("myData.json", jsonContent, { encoding:'utf8', flag: 'as+' });

// OR

fs.writeFile("myData.json", jsonContent, { encoding:'utf8', flag: 'as+' }, (err) => { .... });

For more in-depth information see:

NodeJS Docs | fs.writeFile

NodeJS Docs | fs.writeFileSync

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
svarlitskiy
  • 618
  • 5
  • 11