Search code examples
node.jsmiddlewarenode.js-connect

How does the 'reverse path' in Node.js Connect work?


So I understand that Node.js Connect works like a stack through which it runs, starting from the top and going to the bottom. From the Connect introduction by its author at http://howtonode.org/connect-it it shows an example like

var Connect = require('connect');

module.exports = Connect.createServer(
  require('./log-it')(),
  require('./serve-js')()
);

The article reads

Every request enters the onion at the outside and traverses layer by layer till it hits something that handles it and generates a response. In Connect terms, these are called filters and providers. Once a layer provides a response, the path happens in reverse.

I'm particulary curious about "Once a layer provides a response, the path happens in reverse". How does that happen? Every middleware gets called again, but in reverse order?


Solution

  • No, they don't get called again in reverse, but each middleware has a chance to monkey-patch the request methods and hijack them. It's not ideal.

    // basic logger example
    module.exports = function () {
      return function logger(req, res, next) {
        var writeHead = res.writeHead;
        res.writeHead = function (code, headers) {
          console.log(req.method, req.url, code);
          res.writeHead = writeHead;
          return res.writeHead(code, headers);
        };
        next();
      };
    };
    

    Now, this code has issues because writeHead isn't the only way to set the status code, so it won't catch all requests. But that is the basic way that middleware can catch events on the way out.