This question extends that of What is Node.js' Connect, Express and "middleware"?
I'm going the route of learning Javascript -> Node.js -> Connect -> Express -> ... in order to learn about using a modern web development stack. I have a background in low-layer networking, so getting up and going with Node.js' net
and http
modules was easy. The general pattern of using a server to route requests to different handlers seemed natural and intuitive.
Moving to Connect, I'm afraid I don't understand the paradigm and the general flow of data of this "middleware". For example, if I create some middleware for use with Connect ala;
// example.js
module.exports = function (opts) {
// ...
return function(req, res, next) {
// ...
next();
};
};
and "use" it in Connect via
var example = require('./example');
// ...
var server = connect.createServer();
// ...
server.use(example(some_paramater));
I don't know when my middleware gets called. Additionally, if I'm use()
'ing other middlware, can I be guaranteed on the order in which the middleware is called? Furthuremore, I'm under the assumption the function next()
is used to call the next (again, how do I establish an ordering?) middleware; however, no parameters (req, res, next) are passed. Are these parameters passed implicitly somehow?
I'm guessing that the collection of middleware modules used are strung together, starting with the http
callback -> hence a bunch of functionality added in the middle of the initial request callback and the server ending a response.
I'm trying to understand the middleware paradigm, and the flow of information/execution.
var A = require('./A'), B = require('./B'); app.use(A()); app.use(B());
thenA
would come beforeB
, withA
'snext
invokingB
? Are the parameters then passed implicitly? Else how wouldB
accessreq, res, ect
? – Stylish