title: Unhandled stream error in pipe: write EPIPE in Node.js
body: <p>The idea is to serve screenshots of RTSP video stream with Express.js server. There is a continuously running spawned openRTSP process in flowing mode (it's stdout is consumed by another ffmpeg process):</p>
  
  <pre><code>function spawnProcesses (camera) {
    var openRTSP = spawn('openRTSP', ['-c', '-v', '-t', camera.rtsp_url]),
        encoder = spawn('ffmpeg', ['-i', 'pipe:', '-an', '-vcodec', 'libvpx', '-r', 10, '-f', 'webm', 'pipe:1']);
  
    openRTSP.stdout.pipe(encoder.stdin);
  
    openRTSP.on('close', function (code) {
      if (code !== 0) {
        console.log('Encoder process exited with code ' + code);
      }
    });
  
    encoder.on('close', function (code) {
      if (code !== 0) {
        console.log('Encoder process exited with code ' + code);
      }
    });
  
    return { rtsp: openRTSP, encoder: encoder };
  }
  
  ...
  
  camera.proc = spawnProcesses(camera);
  </code></pre>
  
  <p>There is an Express server with single route:</p>
  
  <pre><code>app.get('/cameras/:id.jpg', function(req, res){
    var camera = _.find(cameras, {id: parseInt(req.params.id, 10)});
    if (camera) {
      res.set({'Content-Type': 'image/jpeg'});
      var ffmpeg = spawn('ffmpeg', ['-i', 'pipe:', '-an', '-vframes', '1', '-s', '800x600', '-f', 'image2', 'pipe:1']);
      camera.proc.rtsp.stdout.pipe(ffmpeg.stdin);
      ffmpeg.stdout.pipe(res);
    } else {
      res.status(404).send('Not found');
    }
  });
  
  app.listen(3333);
  </code></pre>
  
  <p>When i request <code>http://localhost:3333/cameras/1.jpg</code> i get desired image, but from time to time app breaks with error:</p>
  
  <pre><code>stream.js:94
    throw er; // Unhandled stream error in pipe.
          ^
  Error: write EPIPE
      at errnoException (net.js:901:11)
      at Object.afterWrite (net.js:718:19)
  </code></pre>
  
  <p>Strange thing is that sometimes it successfully streams image to <code>res</code> stream and closes child process without any error, but, sometimes, streams image and falls down.</p>
  
  <p>I tried to create <code>on('error', ...)</code> event handlers on every possible stream, tried to change <code>pipe(...)</code> calls to <code>on('data',...)</code> constructions, but could not succeed.</p>
  
  <p>My environment: node v0.10.22, OSX Mavericks 10.9.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I wrapped <code>spawn('ffmpeg',...</code> block with try-catch: </p>
  
  <pre><code>app.get('/cameras/:id.jpg', function(req, res){
  ....
      try {
        var ffmpeg = spawn('ffmpeg', ['-i', 'pipe:', '-an', '-vframes', '1', '-s', '800x600', '-f', 'image2', 'pipe:1']);
        camera.proc.rtsp.stdout.pipe(ffmpeg.stdin);
        ffmpeg.stdout.pipe(res);
      } catch (e) {
        console.log("Gotcha!", e);
      }
  ....
  });
  </code></pre>
  
  <p>... and this error disappeared, but log is silent, it doesn't catch any errors. What's wrong?</p>