Express源碼解析(一)

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

中間件、路由、基于node的http模塊封裝的request和response、還有公用方法,一共只有11個(gè)文件,卻實(shí)現(xiàn)的強(qiáng)大的功能,這代碼質(zhì)量,不得不佩服。按照我的思路一個(gè)個(gè)解析(看源碼要細(xì),慢慢理解

  1. 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文件里。

  1. application.js
    老規(guī)矩先找module.exports的位置
var app = exports = module.exports = {};

導(dǎo)出app對(duì)象,該對(duì)象上有express().xx全部的方法。按調(diào)用順序,直接先看init方法。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容