0

I am creating a system that logs "Infractions" in a JSON file for further use. However, whenever I use fs.writeFile to do som It just deletes the entire file and writes over it. I am trying to get it to add to the already stocked JSON file.

Here's my code:

const saveData = (infraction) =>{


  fs.readFile('infractions.json', function getData(err, data) {
    var json = JSON.parse(data)

    console.log(json)
})



  const completed = (error) = {
   if(error){
     console.error(error)
     return;
   }
  }
 

 
   const jsonData = JSON.stringify(infraction, null, 2)
  

   setTimeout(function(){
fs.writeFile('infractions.json', jsonData,function(completed){
    if(error){
      console.error(error)
      return;
    }
   })
}, 2000);
   



 }

And here's where I define Infraction and call upon the function above:

const infraction = {
    user: target.id,
    reason: reason,
    punishment: punishment
  }

saveData(infraction);

I tried using fs.readFile and JSON.parse, however I could'nt get the variable output to be accessable. It just kept erroring as undefined.

    var json = JSON.parse(data)

    console.log(json)
})
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57

1 Answers1

0

You should use fs.appendFile instead of fs.writeFile.

Siddharth
  • 450
  • 4
  • 10