title: Node & Express: Sending 404 response when using callback
body: <p>Sorry for the poor title but I couldn't think of anything better. First look at the following code snippet:</p>
  
  <pre><code>app.use(function(request, response){
      request.addListener('end', function() {
          parseUrl(request.url, function(urlInfo) {
              if (urlInfo.notFound)
                  response.send(404);
              else if (urlInfo.extension == '.html') {
                  response.render(
                      urlInfo.path, 
                      { 
                          file: urlInfo.filenameWithoutExtension, 
                          url: urlInfo.url, 
                          directory: urlInfo.directory
                      },
                      function(error, html) {
                          if (error) {
                              console.log("Error rendering view: " + error);
                              response.send(404);
                          }
  
                          response.send(html);
                      });
              }
              else
                  file.serve(request, response);
          });
      }).resume();
  });
  </code></pre>
  
  <p>This code does execute fine and serve pages. For certain requests parseUrl will make a call to a web service. The result of this service determines whether we should send a 404 response to the client or not. So when the service needs to be called the callback is invoked after the web request, otherwise the callback is just invoked inline.</p>
  
  <p>The code executes fine but I get a 200 response. Looking at the log files it appears that the response.send(404) is called after the 200 response is sent. So I am assuming that the request.resume() is being called while the web request is taking place. This does make sense.</p>
  
  <p>However whatever I do I can't get this to function how I want. I have tried:</p>
  
  <ul>
  <li>Moving the request.resume to the end of the callback</li>
  <li>Removing app.use and doing a request.resume at the end of the callback.</li>
  </ul>
  
  <p>Generally whatever I do I break the server and it either times out or errors.</p>
  
  <p>I have scoured the web and I am at a loss. If anybody is able to point me in the right direction that would be greatly appreciated. I am obviously missing a vital piece of knowledge here, I am new to node and express, this is my first project.</p>
  
  <p>Thanks in advance.</p>
  
  <p>Cheers,
  Mark</p>
  
  <p>UPDATE:
  Looking at this again and reading <a href="https://github.com/joyent/node/blob/master/doc/api/stream.markdown" rel="nofollow">https://github.com/joyent/node/blob/master/doc/api/stream.markdown</a>. It seems I need to explicitly call pause in the end event when using an asynchronous callback otherwise the stream will close as we return. I will try this later today and report back.</p>