美文网首页
koa 源码解读

koa 源码解读

作者: 努力学习的小丸子 | 来源:发表于2021-07-09 15:56 被阅读0次

源码结构

|- application.js
|- context.js
|- request.js
|- response.js

context.js
context 是使用delegates将节点request和response对象封装到单个对象中,为编写 Web 应用程序和 API 提供了许多有用的方法。

delegate(proto, 'response')
  .method('attachment')
  .method('redirect')
  .method('remove')
  .method('vary')
  .method('has')
  .method('set')
  .method('append')
  .method('flushHeaders')
  .access('status')
  .access('message')
  .access('body')
  .access('length')
  .access('type')
  .access('lastModified')
  .access('etag')
  .getter('headerSent')
  .getter('writable');
// context 对象
koa-context, {
  inspect: [Function: inspect],
  toJSON: [Function: toJSON],
  assert: [Function: assert] {
    equal: [Function (anonymous)],
    notEqual: [Function (anonymous)],
    ok: [Function (anonymous)],
    strictEqual: [Function (anonymous)],
    notStrictEqual: [Function (anonymous)],
    deepEqual: [Function (anonymous)],
    notDeepEqual: [Function (anonymous)]
  },
  throw: [Function: throw],
  onerror: [Function: onerror],
  cookies: [Getter/Setter],
  attachment: [Function (anonymous)],
  redirect: [Function (anonymous)],
  remove: [Function (anonymous)],
  vary: [Function (anonymous)],
  has: [Function (anonymous)],
  set: [Function (anonymous)],
  append: [Function (anonymous)],
  flushHeaders: [Function (anonymous)],
  status: [Getter/Setter],
  message: [Getter/Setter],
  body: [Getter/Setter],
  length: [Getter/Setter],
  type: [Getter/Setter],
  lastModified: [Getter/Setter],
  etag: [Getter/Setter],
  headerSent: [Getter],
  writable: [Getter],
  ......
}

application.js
其中主要实现了uselisten方法。

  • 在 craeteServer 结束后,会触发 callback。
  • 在 cakllback 中调用 compose 将 middleware 传入进去。
  • 当监听到请求的时候,就会按照顺序执行 middleware。
class Application extends Emitter {
constructor(options){
   ...
  }
  listen(...args) {
    debug('listen');
    const server = http.createServer(this.callback());
    return server.listen(...args);
  }
/**
   * Return a request handler callback
   * for node's native http server.
   *
   * @return {Function}
   * @api public
   */

  callback() {
    const fn = compose(this.middleware);

    if (!this.listenerCount('error')) this.on('error', this.onerror);

    const handleRequest = (req, res) => {
      const ctx = this.createContext(req, res);
      return this.handleRequest(ctx, fn);
    };

    return handleRequest;
  }
}

编写自己的中间件并解析koa-static-server的实现原理

中间件是一个方法,且第一个参数是context,第二个参数是next
koa-static-server进行了参数处理和路径解析,然后调用koa-send的send方法。
koa-send根据路径使用fs.createReadStream(path)读出文件内容,并且setHeaders

// koa-static-server/index.js
const send = require("koa-send");
module.exports = function serve(opts) {
  // 解析路径
  let options = opts || {};
  const rootPath = normalize(options.rootPath ? options.rootPath + "/" : "/");
  options.root = resolve(options.rootDir || process.cwd());
  return async (ctx, next) => {
    let path = ctx.path;
    /* Serve folders as specified
        eg. for options:
        rootDir = 'web/static'
        rootPath = '/static'
    'web/static/file.txt' will be served as 'http://server/static/file.txt'
    */

    path = normalize(path.replace(rootPath, "/"));
    /* In case of error from koa-send try to serve the default static file
        eg. 404 error page or image that illustrates error
    */
    try {
      sent = await send(ctx, path, options);
    } catch (error) {
      if (!options.notFoundFile) {
        if (options.last) ctx.throw(404);
      } else {
        sent = await send(ctx, options.notFoundFile, options);
      }
    }

    if (sent && options.last) {
      return;
    } else {
      return next();
    }
  };
};

// koa-send/index.js
module.exports = async function send(ctx, path, opts = {}) {
  const setHeaders = opts.setHeaders;
  if (setHeaders && typeof setHeaders !== "function") {
    throw new TypeError("option setHeaders must be function");
  }
  const root = opts.root ? normalize(resolve(opts.root)) : "";
  path = resolvePath(root, path);
  // 检测文件是否存在,node官网不推荐使用该方式,推荐直接read/write,如果文件不存在就处理错误。
  // 检查文件是否存在而不操作它之后,推荐fs.access()。
  stats = await stat(path);
  if (setHeaders) setHeaders(ctx.res, path, stats);
  // 将文件内容返回
  ctx.set('Content-Length', stats.size)
  ctx.body = fs.createReadStream(path);
  return path;
};

koa-compose

执行步骤:

  • 执行第一个中间件,传入contextnext(通过 dispatch.bind(null, i + 1)获得,在中间件中执行next()函数,即执行了第二个中间件)
  • 执行第二个中间件时,如果方法体中没有执行next()方法,所以不会继续调用dispatch.bind(null, i + 1)方法
  • 执行第二个中间件时,如果方法体中执行next()方法,由于middlewareArray中只有两个中间件,所以执行fn = next,由于koa源码中执行的是fn(ctx).then(handleResponse).catch(onerror);,没有传入next,所以直接执行return Promise.resolve();
// koa 源码
const fn = compose(this.middleware);
fn(ctx).then(handleResponse).catch(onerror);
// koa-compose 源码
var middlewareArray = [
  function(context, next) {
    console.log(1);
    next();
    console.log(3);
  },
  function(context, next) {
    console.log(2);
  }
];
function compose(middleware) {
  // 此处的next 是执行完所有中间件之后执行的回调函数
  return function(context, next) {
    let index = -1;
    return dispatch(0);
    function dispatch(i) {
      // 如果在一个 middleware 中调用了 2 次 next 方法,则会报错
      if (i <= index)
        return Promise.reject(new Error("next() called multiple times"));
      index = i;
      let fn = middleware[i];
      if (i === middleware.length) fn = next;
      if (!fn) return Promise.resolve();
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
      } catch (err) {
        return Promise.reject(err);
      }
    }
  };
}

var fn = compose(middlewareArray);
fn();
// 1
// 2
// 3

相关文章

  • 解读koa源码

    先占坑,3月会开始写没想到拖到4月了 相关链接:解读并实现一个简单的koa-router

  • Koa源码解读

    初始化 执行koa()的时候初始化了一些很有用的东西,包括初始化一个空的中间件集合,基于Request,Respo...

  • koa源码解读

    1、入口 constKoa =require('koa');constapp =newKoa(); require...

  • koa 源码解读

    源码结构 context.jscontext 是使用delegates将节点request和response对象封...

  • koa源码解读指南

    导语:用过node的同学相信都知道koa。截止目前为止,koa目前官方版本最新是2.7.0。本文意在深入分析koa...

  • Koa2源码解读

    此文项目代码:https://github.com/bei-yang/I-want-to-be-an-archit...

  • Koa源码阅读

    Koa源码 继着上文的Co源码以及与Koa的深入理解,开始学习下Koa是怎么写的。我看的版本是1.1.2的。 从p...

  • koa思维导图与源码解读

    思维导图: 源码解读 我们经常会像下边这样用: 1.new Koa生成的实例app具有以下的属性和方法: 2.ap...

  • koa-router @2.0.0 源码解读

    在使用node开发应用时需要用到各种插件,版本不适配会出现各种各样的错误,这时你想直接搜索出解决方案,简直是大海捞...

  • 你不能不知道的Koa实现原理

    前言 什么?这是一篇源码解读文章 ? 那一定很枯燥!不看。 我把 Koa 的核心实现剥离成了 7 个小节,循序渐进...

网友评论

      本文标题:koa 源码解读

      本文链接:https://www.haomeiwen.com/subject/zjqfpltx.html