title: Node.js: How to write() on Write Stream 'finish' event
body: <p>I'm using Node.js streams to go through a text file line by line, make some transforms and output to a SVG file. </p>
  
  <p>I am trying to write one last piece of data (<code>&lt;/svg&gt;</code>) after the processing is done, however by the time the write stream emits the <code>finish</code> event,  attempting to <code>write()</code> will throw <code>Error: write after end</code>.</p>
  
  <p>Is there an elegant way I can solve this?</p>
  
  <p><strong>Note:</strong> The input file is large (around 1GB) so there's no going around the <code>pipe()</code> method due to its I/O and memory management.</p>
  
  <pre><code>var fs = require('fs');
  var split2 = require('split2');
  var through2 = require('through2');
  
  var read_stream = fs.createReadStream('input.txt');
  var write_stream = fs.createWriteStream('output.svg');
  
  write_stream.write('&lt;svg&gt;');
  write_stream.on('finish', function() {
    this.write('&lt;/svg&gt;'); // doesn't work
  });
  
  read_stream
    .pipe(split2())
    .pipe(through2.obj(function(line, encoding, next) {
       this.push(line);
       next();
    }))
    .pipe(write_stream);
  </code></pre>
  
  <h2>Solutions</h2>
  
  <p>Thank you <a href="https://stackoverflow.com/users/4465244/jordan-honeycutt">Jordan</a> &amp; <a href="https://stackoverflow.com/users/2795621/pnre">pNre</a> for helping me figuring this out.</p>
  
  <h3>Solution 1 (generic)</h3>
  
  <p><code>pipe()</code> the write stream with the <code>end:false</code> option and manually <code>end()</code> the stream.</p>
  
  <pre><code>var fs = require('fs');
  var split2 = require('split2');
  var through2 = require('through2');
  
  var read_stream = fs.createReadStream('input.txt');
  var write_stream = fs.createWriteStream('output.svg');
  
  write_stream.write('&lt;svg&gt;');
  
  read_stream
    .pipe(split2())
    .pipe(through2.obj(function(line, encoding, next) {
       this.push(line);
       next();
    }))
    .pipe(write_stream, { end: false });
  
  read_stream.on('end', function() {
    write_stream.end('&lt;/svg&gt;');
  });
  </code></pre>
  
  <h3>Solution 2 (specific to <code>through</code>/<code>through2</code> transform streams)</h3>
  
  <p><a href="https://github.com/rvagg/through2" rel="nofollow noreferrer"><code>through2</code></a> has a flush function that can be used to write the final data.</p>
  
  <pre><code>var fs = require('fs');
  var split2 = require('split2');
  var through2 = require('through2');
  
  var read_stream = fs.createReadStream('input.txt');
  var write_stream = fs.createWriteStream('output.svg');
  
  write_stream.write('&lt;svg&gt;');
  
  read_stream
    .pipe(split2())
    .pipe(through2.obj(function(line, encoding, next) {
      this.push(line);
      next();
    }, function(flush) {
      this.push('&lt;/svg&gt;');
      flush();
    }))
    .pipe(write_stream);
  </code></pre>