title: Node.js, streams, files and error handling
body: <h1>Questions</h1>
  
  <ol>
  <li><p>How do you handle errors gracefully with streams? My code is becoming really ugly and adding <code>.on('error', () =&gt; …)</code> after every <code>.pipe(…)</code> is pain in neck. Is there another way? I read about NodeJS <code>domain</code> but it’s deprecated.</p></li>
  <li><p>How do you handle errors if they occur somewhere in the middle of the stream? In my case, by that time <em>some</em> of the transformed content has already been transferred back to the user.</p></li>
  </ol>
  
  <h1>My use case is:</h1>
  
  <ol>
  <li>User uploads a text file through a typical multipart <code>&lt;form&gt;</code>.</li>
  <li>That file is then transformed on the fly using streams.</li>
  <li>The result, which is a stream, is piped back to the user and download is triggered.</li>
  </ol>
  
  <p>To put it shortly: You add a file, submit the form, and you get a transformed file back.</p>
  
  <h1>Code example</h1>
  
  <p>The following code uses express for handling HTTP requests and busboy for handling file upload:</p>
  
  <pre class="lang-js prettyprint-override"><code>export default Router()
    .get('/', renderPage)
    .post('/', (req, res, next) =&gt; {
      const busboy = new Busboy({ headers: req.headers })
  
      const parser = myParser()
  
      const transformer = myTransformer()
  
      busboy.on('file', (_fieldname, file, filename) =&gt; {
        res.setHeader('Content-disposition', `attachment; filename=${filename}`)
  
        file
          .pipe(parser)
          .on('error', err =&gt; errorHandler(err, req, res))
          .pipe(transformer)
          .on('error', err =&gt; errorHandler(err, req, res))
          .pipe(res)
          .on('error', err =&gt; errorHandler(err, req, res))
      })
        .on('error', err =&gt; errorHandler(err, req, res))
  
      req.pipe(busboy)
        .on('error', err =&gt; errorHandler(err, req, res))
    })
  </code></pre>