title: Node.js close the writestream at the end of the readstream
body: <p>I am reading through a csv file stored on AWS S3. Those csv records are evaluated by a function called filterLogic(). Those record which fail the test need to be written into an error report csv file on AWS S3 as well. For the csv parsing I am using fast-csv.</p>
  
  <p>However, for the last record I get a <code>"Error [ERR_STREAM_WRITE_AFTER_END]: write after end"</code></p>
  
  <p>Where and how do I need to call <code>csvwritestream.end()</code> correctly?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>const AWS = require('aws-sdk');
  const utils = require('./utils');
  const csv = require('fast-csv');
  const s3 = new AWS.S3();
  
  exports.handler = async (event) =&gt; {
      console.log("Incoming Event: ", JSON.stringify(event));
      const bucket = event.Records[0].s3.bucket.name;
      const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
      const message = `File is uploaded in - ${bucket} -&gt; ${filename}`;
      console.log(message);
  
      const splittedFilename = filename.split('.');
      const reportFilename = splittedFilename[0] + "Report." + splittedFilename[1];
      const reportBucket = 'external.transactions.reports';
  
      const csvwritestream = csv.format({ headers: true });
      csvwritestream
          .pipe(utils.uploadFromStream(s3, reportBucket, reportFilename))
          .on('end', function () {
              console.log("Report written to S3 " + reportFilename);
          });
  
      var request = s3.getObject({ Bucket: bucket, Key: filename });
      var stream = request.createReadStream({ objectMode: true })
          .pipe(csv.parse({ headers: true }))
          .on('data', async function (data) {
              stream.pause();
              console.log("JSON: " + JSON.stringify(data));
              var response = await utils.filterLogic(data);
              if (response.statusCode !== 200) {
                  await csvwritestream.write(data);
                  console.log("Data: " + JSON.stringify(data) + " written."); 
              }
              stream.resume();
          })
          .on('end', function(){
              csvwritestream.end();   
          });
      return new Promise(resolve =&gt; {
          stream.on('close', async function () {
              csvwritestream.end();
              resolve();
          });
      });
  };</code></pre>
  </div>
  </div>
  </p>