2

I want to write logs into a Json file

newEntry =  "User: "  + lastUsername + " Time: "+now+ " Door: "+IOSDoor;
lastUserOpenClose += newEntry;

jsonString = JSON.stringify(lastUserOpenClose);

fs.writeFile("lastUserOpenClose.json", lastUserOpenClose, function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("Server-Log: The file was saved!");
    }
});

But I'm overwriting the logs. How to write somthing into a json file and don't overwrite the old logs?

Rob Scott
  • 7,921
  • 5
  • 38
  • 63
alexohneander
  • 519
  • 3
  • 7
  • 22
  • 1
    possible duplicate of [How to append to a file in Node?](http://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node) – Ben Fortune Aug 14 '14 at 10:18
  • 1
    Consider using logging module like [log.js](https://github.com/visionmedia/log.js/) or [bunyan](https://github.com/trentm/node-bunyan) – Salman Aug 14 '14 at 11:07

1 Answers1

11

You should use the fs.appendFile

Example:

fs.appendFile('message.txt', 'data to append', function (err) {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});