LeeeeeeM / blog

daily blog
0 stars 0 forks source link

express如何实现中间件? #6

Open LeeeeeeM opened 6 years ago

LeeeeeeM commented 6 years ago

Node的原理决定了它面向请求的应用场景。类似Nginx的事件驱动,底层区别也不大。 每一条请求,都是封装了同一个app对象,所有有用的没有的东西都是挂在它上面。所以,副作用很大,一不小心就暴露了安全数据。这个暂且不谈,Express的中间件原理给了它强大的生命力。如何实现?暂且抛开异步操作,我们不需要在函数内使用大量的async/await G/yield。

LeeeeeeM commented 6 years ago
function express() {

  var middlewares = [];

  var app = function(req, res) {
    var i = 0;
    function next() {
      var task = middlewares[i++];
      if (!task) {
        return;
      }
      task(req, res, next);
    }
    setTimeout(next);
  }

  app.use = function(fn) {
    middlewares.push(fn);
  };

  return app;
}

// var http = require('http');
// var app = express();

// http.createServer(app).listen(3000, function() {
//     console.log('listening 3000');
// });

// function middleware1(req, res, next) {
//     console.log('middleware1 before next()');
//     next();
//     console.log('middleware1 after next()');
//     res.end('helloworld');
// }

// function middleware2(req, res, next) {
//     console.log('middleware2 before next()');
//     next();
//     console.log('middleware2 after next()');
// }

// function middleware3(req, res, next) {
//     console.log('middleware3 before next()');
//     next();
//     console.log('middleware3 after next()');
// }

// app.use(middleware1);
// app.use(middleware2);
// app.use(middleware3);