Skip to content

Instantly share code, notes, and snippets.

@nodew
Last active March 29, 2017 13:15
Show Gist options
  • Save nodew/c6e1fd846d437f52f2f9fc726dd70cf6 to your computer and use it in GitHub Desktop.
Save nodew/c6e1fd846d437f52f2f9fc726dd70cf6 to your computer and use it in GitHub Desktop.
to understand the middlewares of express better
var proto = {};
function express() {
var app = function(ctx, cb) {
app.handle(ctx, cb);
}
app.__proto__ = proto;
app.stack = [];
return app;
}
proto.use = function (fn) {
this.stack.push(fn);
}
proto.handle = function (ctx, out) {
var self = this;
var index = 0;
var done = out || function() {};
function next(error) {
// error handler first
// get fn in stack serially
var fn = self.stack[index++];
// if no function in stack, done
if (!fn) {
setImmediate(done);
return;
}
/**
* a middleware function is defined as follow:
* function(ctx, next) {
* do something..
* next();
* do something else..
* }
*/
fn(ctx, next);
}
next();
}
// -------------------- test --------------------
var app = express();
app.use(function(ctx, next) {
ctx.a = 1;
next();
console.log("test");
});
app.use(function(ctx, next) {
ctx.b = 2;
console.log(ctx);
next();
});
// in express, should be app(req, res), and `req` `res` is given by http module
app({}, function(){
console.log('every thing is ok');
});
// the out put is
// { a: 1, b: 2 }
// test
// every thing is ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment