title: Node-request - How to determine if an error occurred during the request?
body: <p>I'm trying to leverage the <a href="https://github.com/voxpelli/node-request">node-request module</a>, but the documentation isn't that great. If I make a request to a valid resource and pipe it to a Writable Stream, everything works fine. However, if I make a request to an invalid object, the Writable Stream is still created. Example, take the following snippet:</p>
  
  <pre><code>var x = request("http://localhost:3000/foo.jpg");
  var st = fs.createWriteStream("foo.jpg");
  x.pipe(st);
  </code></pre>
  
  <p>If the foo.jpg resource exists on the server, the data is piped to the stream, and it creates the file fine on the server. However, if foo.jpg <strong>does not</strong> exist on the server, a blank container file is still created. There appears to be no error event or anything that can be leveraged to determine if the request returned a 404. I've tried something like the following:</p>
  
  <pre><code>var x = request("http://localhost:3000/foo.jpg", function(err, response, body) {
      if(response.statusCode === 200) {
          // Success
          var st = fs.createWriteStream("foo.jpg");
          x.pipe(st);
      }
  });
  </code></pre>
  
  <p>And also:</p>
  
  <pre><code>request("http://localhost:3000/foo.jpg", function(err, response, body) {
      if(response.statusCode === 200) {
          // Success
          var x = response.request;
          var st = fs.createWriteStream("foo.jpg");
          x.pipe(st);
      }
  });
  </code></pre>
  
  <p>To no avail. The idea is pretty simple; I just want to copy a file identified by the URL to the local server. If the request is invalid (404, etc), don't pipe the file; if the request is valid, pipe the file. Any suggestions?</p>