每天學(xué)一點(diǎn),分享我的所得。
Express算是nodejs最知名的框架了。即使nodejs掌握的不多,也能使用簡單幾條語句,輕松創(chuàng)建web服務(wù)器。如此便捷,那它是如何工作的呢,今天我們就來瞧一瞧(Version:4.17.1)。
首先,看一下express源碼的結(jié)構(gòu)。

-
express.js
項(xiàng)目入口文件。先找導(dǎo)出部分
// 默認(rèn)導(dǎo)出 createApplication函數(shù)
exports = module.exports = createApplication;
這里有一個(gè)知識(shí)點(diǎn):exports和module.exports的區(qū)別和用法。簡單說一下。module.exports和exports默認(rèn)指向同一個(gè)地址一個(gè)空對(duì)象,module.exports為nodejs文件的默認(rèn)導(dǎo)出。當(dāng)module.exports指向了新的對(duì)象,則exports指向的地址對(duì)導(dǎo)出無效。上面這種寫法,是將exports和module.exports進(jìn)行強(qiáng)綁定。
接下來看這個(gè)導(dǎo)出函數(shù)
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
// expose the prototype that will get set on requests
app.request = Object.create(req, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
// expose the prototype that will get set on responses
app.response = Object.create(res, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
app.init();
return app;
}
利用mixin函數(shù)給app對(duì)象添加屬性,false不覆蓋屬性。proto這個(gè)文件里有很多方法都是app.xx的屬性,之后以req和res為原型創(chuàng)建對(duì)象,并添加新屬性app。暴漏出去。之后執(zhí)行proto里面的init方法。返回app對(duì)象。
由此可見所有的秘密都在application.js文件里。
- application.js
老規(guī)矩先找module.exports的位置
var app = exports = module.exports = {};
導(dǎo)出app對(duì)象,該對(duì)象上有express().xx全部的方法。按調(diào)用順序,直接先看init方法。