title: Write / add data in JSON file using Node.js
body: <p>I am trying to write JSON file using node from loop data, e.g.:</p>
  
  <pre class="lang-js prettyprint-override"><code>let jsonFile = require('jsonfile');
  
  for (i = 0; i &lt; 11; i++) {
      jsonFile.writeFile('loop.json', "id :" + i + " square :" + i * i);
  }
  </code></pre>
  
  <p>outPut in loop.json is:</p>
  
  <pre><code>id :1 square : 1
  </code></pre>
  
  <p>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:</p>
  
  <pre class="lang-json prettyprint-override"><code>{
     "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
        }
     ]
  }
  </code></pre>
  
  <p>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</p>
  
  <pre class="lang-js prettyprint-override"><code>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 &lt; 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 &lt; 5; i++) {
              obj.table.push({
                  id: i,
                  square: i * i
              });
          }
  
          let json = JSON.stringify(obj);
          fs.writeFile('myjsonfile.json', json);
      }
  });
  </code></pre>