koa浅析

koa功能划分

koa作为base node.js的下一代web应用框架,其具有简洁、健壮、富有表现力等特点。由Express幕后的原班人马打造,充分利用async + await + promise的特定,有效的规避了回调函数,且增强了错误处理。其核心主要包括两个部分,一个是koa本身,一个是中间件的流程控制koa-composekoa源码解析)。
koa关键目录

application.js

application.jskoa的入口文件,对外暴露了application这个类,继承nodeevents

const Emitter = require('events');
const http = require('http');

module.exports = class Application extends Emitter {
	constructor(options) {
		super();
		options = options || {};
	    this.proxy = options.proxy || false;
	    this.subdomainOffset = options.subdomainOffset || 2;
	    this.proxyIpHeader = options.proxyIpHeader || 'X-Forwarded-For';
	    this.maxIpsCount = options.maxIpsCount || 0;
	    this.env = options.env || process.env.NODE_ENV || 'development';
	    if (options.keys) this.keys = options.keys;
	    this.middleware = [];
	    this.context = Object.create(context);
	    this.request = Object.create(request);
	    this.response = Object.create(response);
	    if (util.inspect.custom) {
	      this[util.inspect.custom] = this.inspect;
	    }
	}
	use(fn) {
		this.middleware.push(fn);
    	return this;
	}
	listen(...args) {
		const server = http.createServer(this.callback());
    	return server.listen(...args);
	}
};

application就是应用,通过实例化该应用,在应用上挂载应用属性,并暴露了公用的api,其中使用最频繁的有两个,一个是listen,一个是uselisten就是使用nodehttp模块调用http.createServer进行服务创建,传入callback函数,用于指定当接收到客户端请求时所需执行的处理,这callback包含着应用的核心处理逻辑。主要包含了中间件的compose处理,上下文的处理,对reqres的特殊处理。use函数在应用中使用的最多,功能也比较简单,主要就是收集中间件,pushmiddleware数组中,然后交给koa-compose进行中间价流程控制,use函数return this因此可以进行级联操作。

const Koa = require('koa');
// 实例化应用
const app = new Koa();
// 添加中间件
app.use(async (ctx, next) => {});
// 创建并启动server服务
app.listen(3000, () => {
	console.log('server is running: http://loacalhost:30000')
});

context.js

const delegate = require('delegates');

const proto = module.exports = {};
delegate(proto, 'response')
delegate(proto, 'request')

context.js就是koa的应用上下文ctx,其只是简单的对外暴露了一个对象,对象里面挂载了一些属性和方法,包括assert断言,cookies操作、throw直接报错等。其重点在与使用delegaterequestreponse的一些方法的代理,可以直接使用ctx使用requestreponse对象的一些方法和属性,十分便捷。

request.js response.js

// request.js
module.exports = {}
// response.js
module.exports = {}

request.jsresponse.js都是简单对对外暴露一个对象,主要是定义了对callback函数使用的原生reqres对象进行操作,如操作headersbodyscoket等。其大量使用了访问器属性,使用getset函数对属性进行读取和写入操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章