# 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
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
用来处理事件订阅相关,原型上具有on
、emit
等方法。proto
这个后面再详细说明。
接着在函数上定义了两个属性:request
和response
。他们的原型分别指向了http.IncomingMessage.prototype
和http.ServerResponse.prototype
。推测:这是原始的请求和相应对象。并且在此之上进行了扩展,添加了app
这个属性,并将value
指向了函数本身。
最后调用init
方法进行初始化,这个方法定义在proto
这个对象上,主要在app
上添加了一些变量和事件。