skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    I got this working for all instances after removed utf8.

    Perhaps the error occured because my JSON was invalid (it was a proof of concept script).


  2. You are passing in too many arguements 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 indepth information see:

    NodeJS Docs | fs.writeFile

    NodeJS Docs | fs.writeFileSync

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search