title: JavaScript: Appending a post request json string to existing json file
body: <p>I have a simple express app that takes a post request with some JSON data. I'd like to take that data and append it to an existing json file (If it exists). Key value pairs may be different. My current version pushes an object to an array of objects. Ideally, I'd like to add just another key/value pair:</p>
  
  <pre><code>app.post('/notes', function(req, res){
    var body = "";
    req.on('data', function(chunk){
      body += chunk;
    });
    req.on('end', function(){
      fs.readFile(__dirname + '/data/notes.json', function(err, data){
        if (err) throw err;
        console.log(body);
        var fileObj = JSON.parse(data.toString());
        var postObj = JSON.parse(body);
        fileObj.notes.push(postObj);
        var returnjson = JSON.stringify(fileObj);
        fs.writeFile(__dirname + '/data/notes.json', returnjson, function(err){
          if (err) throw err;
          res.send(returnjson);
        });
      });
    });
  });
  </code></pre>
  
  <p>Example of what might be in notes.json:</p>
  
  <pre><code>{"note": "Dear Diary: The authorities have removed the black pants from the couch"}
  </code></pre>
  
  <p>This works, but I'm having trouble wrapping my head around appending whatever json comes in the post (Let's assume there is no nested data in this case).</p>
  
  <p>EDIT: Not the same as just appending to a file. Needs to append to an object within a file.</p>