nodejs append inside json file in array format

javascript, node.js

Solution

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

- Read file, parse it, append data to array, serialize, replace file content.

- Switch to different file format. Actually CSV is good enough to store table-like data and is 'appendable'.

Problem

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); } }); ```

Original source