title: Removing the last character from file stream in node.js (fs module)
body: <p>Using node.js, I am trying to build an array of objects and write them to a file. To do this, I'm using the built in fs library.</p>
  
  <p>After calling 
  <code>var file = fs.createWriteStream('arrayOfObjects.json');</code> and <code>file.write('[')</code> I run several asynchronous functions to eventually append objects like this:</p>
  
  <p><code>file.write(JSON.stringify(objectToAppend) + ',\n')</code></p>
  
  <p>I can determine when all of the objects have stopped appending, and this is where I run <code>file.write(']')</code> and <code>file.end()</code>. <em>My problem is that adding the last comma to the end of the last object causes the JSON to be invalid.</em></p>
  
  <p>It is very difficult to determine where and when the last object is being created due to the asynchronous nature of the script, so I was wondering if there is a way to strip or remove characters from a file-stream. If so, I could do this before adding the last <code>']'</code> character.</p>
  
  <p>I could do this manually, but I was hoping to pipe this to another application. The only solution I've thought about is using the <code>fs.truncate()</code> function, however this doesn't seem to work for file streams, and neither <code>file.length</code> or <code>file.length()</code> will give me the length of the contents because it is not a string so it's difficult to determine how or where to truncate the file.</p>
  
  <p>For now I have just been adding <code>'{}]'</code> to the end of the array to make it valid JSON, but this empty object may cause some problems later.</p>
  
  <p>Also <strong>note: the array of objects I am writing in this stream is VERY large, so I would rather not end the stream and re-open the file</strong>.</p>