# Express 源码解析

# 入口

var app = express()
1

由此可见,express内部导出的是一个函数。以下为此函数。

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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

函数内部又返回了一个函数app,我们定义的app变量返回值可见是一个函数。mixin函数本质上是在第一个参数上合并上第二个参数的属性,有点类似于Object.assign(),但是如果有同名的参数,则以第一个为主。EventEmitter用来处理事件订阅相关,原型上具有onemit等方法。proto这个后面再详细说明。

接着在函数上定义了两个属性:requestresponse。他们的原型分别指向了http.IncomingMessage.prototypehttp.ServerResponse.prototype。推测:这是原始的请求和相应对象。并且在此之上进行了扩展,添加了app这个属性,并将value指向了函数本身。

最后调用init方法进行初始化,这个方法定义在proto这个对象上,主要在app上添加了一些变量和事件。

上次更新时间: 9/12/2021, 10:30:35 PM