Colorful

Colorful - 一枚数字艺术家的自留地

马上订阅 Colorful RSS 更新: https://xiaoa.name/feed.xml

KOA 源码阅读系列(一) - 理解 KOA 中间件的执行

2016年4月10日 08:00

源码阅读系列的开篇就不多废话了,开门见山。

首先看添加中间件的入口 app.use 的源码

/**
 * Use the given middleware `fn`.
 *
 * @param {GeneratorFunction} fn
 * @return {Application} self
 * @api public
 */

app.use = function (fn) {
  if (!this.experimental) {
    //es7 async functions are not allowed,
    //so we have to make sure that `fn` is a generator function
    assert(
      fn && "GeneratorFunction" == fn.constructor.name,
      "app.use () requires a generator function"
    );
  }
  debug("use % s", fn._name || fn.name || "-");

  // 主要就是做这个事情
  // 根据上面的 assert,这里的 fn 均为 generator function
  this.middleware.push(fn);
  return this;
};

接着,来看一下 Server 是怎么起来的

/**
 * Shorthand for:
 *
 *    http.createServer (app.callback...

剩余内容已隐藏

查看完整文章以阅读更多