> 因項(xiàng)目需要使用koa模擬服務(wù)器返回接口涝焙,研究下koa加載過(guò)程
1卑笨、nodejs下的require, 一切node模塊的加載都是從node_modules開(kāi)始的,打開(kāi)koa模塊package.json 仑撞,僅關(guān)注入口main屬性對(duì)應(yīng)的啟動(dòng)項(xiàng)湾趾,和dependencies 屬性的依賴項(xiàng),npm模塊的依賴會(huì)檢查如果dependencies下對(duì)應(yīng)的文件是否存在派草,如果不存在則加載搀缠,參考樸靈深入淺出nodejs
{
"main": "lib/application.js",
"dependencies": {
"accepts": "^1.3.5",
"cache-content-type": "^1.0.0",
"content-disposition": "~0.5.2",
"content-type": "^1.0.4",
"cookies": "~0.7.1",
"debug": "^3.1.0",
"delegates": "^1.0.0",
"depd": "^1.1.2",
"destroy": "^1.0.4",
"error-inject": "^1.0.0",
"escape-html": "^1.0.3",
"fresh": "~0.5.2",
"http-assert": "^1.3.0",
"http-errors": "^1.6.3",
"is-generator-function": "^1.0.7",
"koa-compose": "^4.1.0",
"koa-convert": "^1.2.0",
"koa-is-json": "^1.0.0",
"on-finished": "^2.3.0",
"only": "~0.0.2",
"parseurl": "^1.3.2",
"statuses": "^1.5.0",
"type-is": "^1.6.16",
"vary": "^1.1.2"
},
"devDependencies": {
"eslint": "^3.17.1",
"eslint-config-koa": "^2.0.0",
"eslint-config-standard": "^7.0.1",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^2.1.1",
"jest": "^20.0.0",
"supertest": "^3.1.0"
}
}
2、app.use 中間件, 其實(shí)就是做了個(gè)記錄近迁,把傳入會(huì)掉push到middleware艺普,callback函數(shù)會(huì)在http.createServer中以高階函數(shù)的形式返回,注入ctx和之前push到middleware中的回調(diào)。所以當(dāng)改變url觸發(fā)了http.createServer 歧譬,會(huì)執(zhí)行use中的函數(shù)岸浑。
//中間件
use(fn) {
if (typeof fn !== 'function') throw new TypeError('middleware must be a function!');
if (isGeneratorFunction(fn)) {
deprecate('Support for generators will be removed in v3. ' +
'See the documentation for examples of how to convert old middleware ' +
'https://github.com/koajs/koa/blob/master/docs/migration.md');
fn = convert(fn);
}
debug('use %s', fn._name || fn.name || '-');
this.middleware.push(fn);
return this;
}
//監(jiān)聽(tīng)
listen(...args) {
debug('listen');
const server = http.createServer(this.callback());
return server.listen(...args);
}
//監(jiān)聽(tīng)回調(diào)
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;
}
3、自己開(kāi)發(fā)use
//class router
let data = {}
class router {
constructor(str,fun){
Object.defineProperty(router,"data",{value:{}})
}
get(str,fun){
router.data[str] = fun;
}
async main(params,next){
await next();
let reg = /\/.*/g;
let {path} = params;
router.data[path](params);
}
}
module.exports=new router;
//執(zhí)行
const Koa = require('koa');
const app = new Koa();
const router = require("./router");
router.get("/getData",async arg=>{
arg.body="hello world"
})
app.use(router.main); //響應(yīng)
app.listen(3000);