title: How to change NodeJS Request Stream response
body: <p>I'm somewhat new to NodeJS, and current I used Express and Request ( <a href="https://github.com/request/request" rel="nofollow">https://github.com/request/request</a> ) to forward my app request to REST api server, current my code shown below: </p>
  
  <pre><code>app.use('/rest/*', function(req, res) {
      req.pipe(request('http://ipaddress/api')).pipe(res);
  });
  </code></pre>
  
  <p>this code works when the REST API server is OK, but if the rest api server goes down, my nodejs app also goes down, because request stream will fail and the error is not caught by my app.
  I checked the Request github page, it provides one way to handle the stream error, like</p>
  
  <pre><code>app.use('/rest/*', function(req, res) {
      req.pipe(request('http://ipaddress/api').on('error', function(err) {
          console.log(err);
      })).pipe(res);
  });
  </code></pre>
  
  <p>this can only log the error and prevent my NodeJS app crashing, but I want to change the response when error occurred so that the changed response can be piped to final one, for example, what I want to do in pseudocode:</p>
  
  <pre><code>app.use('/rest/*', function(req, res) {
      req.pipe(request('http://ipaddress/api').on('error', function(err) {
          console.log(err);
          // what I want to do in pseudocode
          response.statusCode = 500;
          response.json = {
              reason: err.errno 
          };
      })).pipe(res);
  });
  </code></pre>
  
  <p>Are there any ways to solve my problems?  Thanks for any ideas!</p>