title: Close stream when finished
body: <p>I am streaming HTML 5 video with Express using <code>fs.createReadStream(path).pipe(res);</code> which eventually causes the error <code>Error: EMFILE: too many open files</code> if I refresh the page too many times (in the thousands). I assume I need to perform some kind of cleanup and close the file to prevent this but am unsure what needs to be done.</p>
  
  <p>I am creating a read stream every time the user seeks to a part of the video which the client has not loaded which makes this problem happen in a matter of minutes. Task manager shows the same file open hundreds of times so it appears to never get closed.</p>
  
  <p>Relevant part of the stream function:</p>
  
  <pre><code>fs.stat(path, function(err, stats) {
    var size = stats.size;
    var range = req.headers.range;
  
    if (range) {
      var parts = range.replace(/bytes=/, '').split('-');
      var start = parseInt(parts[0]);
      var end = parts[1] ? parseInt(parts[1]) : size - 1;
      var chunksize = (end - start) + 1;
  
      res.writeHead(206, {
        'Content-Range': 'bytes ' + start + '-' + end + '/' + size,
        'Accept-Ranges': 'bytes',
        'Content-Length': chunksize,
        'Content-Type': 'video/mp4'
      });
  
      fs.createReadStream(path, {start: start, end: end}).pipe(res);
    } else {
      res.writeHead(200, {
        'Content-Length': size,
        'Accept-Ranges': 'bytes',
        'Content-Type': 'video/mp4'
      });
  
      fs.createReadStream(path).pipe(res);
    }
  });
  </code></pre>