connect模块

2019-12-21  本文已影响0人  9吧和9说9话

Connect is an extensible HTTP server framework for node using "plugins" known as middleware.

Connect提供了一种中间件的机制来组织web server应用。
由TJ 大神的出品,包括express等也是基于此实现。
而且模块本身也是非常简洁,总计不到300行代码,非常适合从源码学习nodejs。

connect内部结构

function createServer() {
  function app(req, res, next){ app.handle(req, res, next); }
  app.route = '/';
  app.stack = []; // 中间件stack
  return app;
}

主要提供的api

app.use

// 添加中间件到stack中(简化代码)
app.use(route, fn)
use = function use(route, fn) {
  this.stack.push({ route: path, handle:  fn});
}

app.handle

// 处理请求的具体逻辑(简化代码)
handle = function handle(req, res, out) {
  var index = 0;
  var stack = this.stack;
  function next(err) { 
    // 获取要执行的队列
    // 同时下标后移
    var layer = stack[index++];
    // 比较layer.route  和当前req 和pathname
    // path.toLowerCase().substr(0, route.length) == route.toLowerCase()
    // 递归调用
    call(layer.handle, route, err, req, res, next)
  }
  // 启动队列调用
  next();
}

call内部调用next 实现递归

function call(handle, route, err, req, res, next) {
  // 其他容错机制
  ...
  // 递归执行后续中间件
  next(err);
}

参考:connect

上一篇 下一篇

猜你喜欢

热点阅读