title: Add object to json file - Node.js
body: <p>I'm trying to add an object to a very large JSON file in Node.js (but only if the id doesn't match an existing object). What I have so far:</p>
  
  <p><strong>example JSON file:</strong></p>
  
  <pre><code>[
    {
      id:123,
      text: "some text"
    },
    {
      id:223,
      text: "some other text"
    }
  ]
  </code></pre>
  
  <p><strong>app.js</strong></p>
  
  <pre><code>var fs = require('fs');     
  var jf = require('jsonfile')
  var util = require('util')    
  var file = 'example.json'
  
  // Example new object
  var newThing = {
    id: 324,
    text: 'more text'
  }
  
  // Read the file
  jf.readFile(file, function(err, obj) {
    // Loop through all the objects in the array
    for (i=0;i &lt; obj.length; i++) {
      // Check each id against the newThing
      if (obj[i].id !== newThing.id) {
        found = false;
        console.log('thing ' + obj[i].id + ' is different. keep going.');
      }else if (obj[i].id == newThing.id){
        found = true;
        console.log('found it. stopping.');
        break;
      }
    }
    // if we can't find it, append it to the file
    if(!found){
      console.log('could not find it so adding it...');
      fs.appendFile(file, ', ' + JSON.stringify(newTweet) + ']', function (err) {
        if (err) throw err;
        console.log('done!');
      });
    }
  })
  </code></pre>
  
  <p>This is <em>so</em> close to what I want. The only problem is the trailing <code>]</code> character at the end of the JSON file. Is there a way to delete it using the file system API or something? Or is there a much easier way to do exactly what I want?</p>