Write / add data in JSON file using Node.js

I am trying to write JSON file using node from loop data, e.g.:

let 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

const fs = require('fs');

let obj = {
    table: []
};

fs.exists('myjsonfile.json', function(exists) {

    if (exists) {

        console.log("yes file exists");

        fs.readFile('myjsonfile.json', function readFileCallback(err, data) {

            if (err) {
                console.log(err);
            } else {
                obj = JSON.parse(data);

                for (i = 0; i < 5; i++) {
                    obj.table.push({
                        id: i,
                        square: i * i
                    });
                }

                let json = JSON.stringify(obj);
                fs.writeFile('myjsonfile.json', json);
            }
        });
    } else {

        console.log("file not exists");

        for (i = 0; i < 5; i++) {
            obj.table.push({
                id: i,
                square: i * i
            });
        }

        let json = JSON.stringify(obj);
        fs.writeFile('myjsonfile.json', json);
    }
});

8 Answers
8

Leave a Comment