0

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?

Willem Mulder
  • 12,974
  • 3
  • 37
  • 62

1 Answers1

1

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.

Tim Caswell
  • 439
  • 3
  • 3
  • Clear, thanks! I would however suggest extending Connect to support middleware that has two 'directions', down and up, which would make the process more transparent. The down function would be called 'inwards the onion' and the up function would be called 'outwards', i.e. the reverse path. – Willem Mulder Apr 23 '13 at 14:26
  • FWIW, I just gave a talk about a new web interface for node that is much easier to compose. https://github.com/creationix/moonslice-node/blob/master/slides/slides.md – Tim Caswell Apr 23 '13 at 14:30