5

I want the nodejs to append all the data in the JSON format in following format

    [{
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   }, {
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   },{
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   }]

And I want the nodejs to append more data. I m trying append but it's appending like this

{
  "name": "admin",
  "message": "dfd",
  "datetime": "2014-06-03 13:01:39"
}{
  "name": "admin",
  "message": "dfd",
  "datetime": "2014-06-03 13:01:39"
}

I m using the following code to append

    myData= { "name": "sam" , "message": "hi how are you", "datetime": "2014-5-1 4:4:4" };

    fs.appendFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
        if(err) {
          console.log(err);
        }
    });
3
  • what is code used for appending? Commented Jun 3, 2014 at 9:33
  • @A-0- question is updated Commented Jun 3, 2014 at 10:01
  • You might need to parse the array from the file as a javascript array, append your new data to the array and then save the array in the file. Commented Jun 3, 2014 at 10:06

1 Answer 1

9

JSON is not 'appendable' format. You have two options here:

  1. Read file, parse it, append data to array, serialize, replace file content.
  2. Switch to different file format. Actually CSV is good enough to store table-like data and is 'appendable'.
Sign up to request clarification or add additional context in comments.

1 Comment

It will. Though it is definitely not the optimal way in terms of disk space and performance. :) CSV has less metadata and you don't need to read the entire file to add a few lines.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.