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函數對屬性進行讀取和寫入操作。

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