title: Append JSON to a file using node streams
body: <p>Based on what I have read <a href="https://stackoverflow.com/a/43370201/1252748">here</a>, I'm using <code>fs.createWriteStream</code> to write some JSON to a file. I am processing the data in chunks of about 50. So at the beginning of the script, I open my streamand then use a function to pass it in, along with some JSON, which is working pretty well for writing.</p>
  
  <pre><code>const myStream = fs.createWriteStream(
    path.join(RESULTS_DIR, `my-file.json`),
    {
      flags: 'a'
    }
  )
  
  
  function appendJsonToFile(stream, jsonToAppend) {
    return new Promise((resolve, reject) =&gt; {
      try {
        stream.write(JSON.stringify(jsonToAppend, null, 2)
        resolve('STREAM_WRITE_SUCCESS')
      } catch (streamError) {
        reject('STREAM_WRITE_FAILURE', streamError)
      }
    })
  }
  
  appendJsonToFile(myStream, someJson)
  </code></pre>
  
  <p>However, because each piece of data to be written is an array of objects, the structure I eventually get in my file will look like this:</p>
  
  <pre><code>[
      {
          "data": "test data 1",
      },
          {
          "data": "test data 2",
      }
  ][
      {
          "data": "test data 3",
      },
          {
          "data": "test data 4",
      }
  ]
  </code></pre>
  
  <h3>How can I append these pieces of data so that the result is properly formatted JSON, rather than just a series of arrays?</h3>