express 中间件的简单实现

323 阅读1分钟

express 想必前端攻城狮多多少少都有过一定的使用。所以对中间件的使用也很频繁,代码中处处可以看到如下代码


app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});
app.use(express.static('public'));
...

但是它是如何实现的呢?其实搞懂之后发现它的实现其实很简单但是也很巧妙,话不多说直接撸代码吧

var http = require('http');
function express(){
    var funcs = [];

    var expr = function(req,res){
        var i = 0;
        function next(){            
            var task = funcs[i++];
            if(!task) return;
            task(req,res,next);
        }
        next();
    }
    expr.use=function(f){
        funcs.push(f);
    }
    return expr;
}
var app = express();

app.use(function(req,res,next){
    console.log('haha');
    next();
});
app.use(function(req,res,next){
    console.log('hehe');
    next();
});
app.use(function(req,res){
    res.end("there is nothing happened");
});

http.createServer(app).listen('3000', function(){
    console.log('Express server listening on port 3000');
});