title: How do I capture a "response end" event in node.js+express?
body: <p>I'd like to write an express middleware function that sets up a listener on the response's 'end' event, if one exists.  The purpose is to do cleanup based on the http response code that the end handler decided to send, e.g. logging the response code and rollback/commit of a db transaction.  i.e., I want this cleanup to be transparent to the end caller.</p>
  
  <p>I'd like to do something like the following in express:</p>
  
  <p>The route middleware</p>
  
  <pre><code>function (req, res, next) {
     res.on ('end', function () {
        // log the response code and handle db
        if (res.statusCode &lt; 400) { db.commit() } else { db.rollback() }
     });
     next();
  }
  </code></pre>
  
  <p>The route:</p>
  
  <pre><code>app.post ("/something", function (req, res) { 
      db.doSomething (function () {
         if (some problem) {
            res.send (500);
         } else {
            res.send (200);
         }
      });
   }
  </code></pre>
  
  <p>When I try this, the 'end' event handler never gets called.  The same for <code>res.on('close')</code>, which I read about in another post.  Do such events get fired?</p>
  
  <p>The only other way I can think of doing this is wrapping <code>res.end</code> or <code>res.send</code> with my own version in a custom middleware.  This is not ideal, because <code>res.end</code> and <code>res.send</code> don't take callbacks, so I can't just wrap them, call the original and then do my thing based on the response code that got set when they call me back (because they won't call me back).</p>
  
  <p>Is there a simple way to do this?</p>