user6254448 user6254448 - 7 months ago 3200
Javascript Question

write/add data in JSON file using node.js

i am trying to write JSON file using node from loop data
eg

var jsonfile = require('jsonfile');
for (i=0; i <11 ; i++){
jsonfile.writeFile('loop.json', "id :" + i + " square :" + i*i);
}


outPut in loop.json is

id :1 square : 1


but i want output file like this (below) and also if i run that code again it should add that new output as elements in same existing JSON file

{
"table": [
{
"Id ": 1,
"square ": 1
},
{
"Id ": 2,
"square ": 3
},
{
"Id ": 3,
"square ": 9
},
{
"Id ": 4,
"square ": 16
},
{
"Id ": 5,
"square ": 25
},
{
"Id ": 6,
"square ": 36
},
{
"Id ": 7,
"square ": 49
},
{
"Id ": 8,
"square ": 64
},
{
"Id ": 9,
"square ": 81
},
{
"Id ": 10,
"square ": 100
}
]
}


i want to use same file that i created 1st time but whenever i run that code new elements should add in that same file

please ignore my grammar -_-

Answer

If this json file won't become too big over the time you should try:

  1. Create a javascript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it like

    obj.table.push({id: 1, square:2});
    
  3. Convert it to a json

    var json = JSON.stringify(obj);
    
  4. use fs to write the file to disk

    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. if you want to append it read the json file and convert it back to an object

    fs.readFile('/etc/passwd', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back to disk
    };
    

This will work for data big as 100 MB max effectively. Over this limit you should use a database engine.

UPDATE:

Create a function which return the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existance named fs.stat(path, callback). With this you can check if the file exists. If it exists use the read function if its not use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contains a stats object which will be null if the file does not exists.

Comments