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; }
很明显在调用 express()本质是执行了一段 createApplication 函数
2. app.listen()做了哪些事情❓
这里你可能会有两个疑问:
2.1 app不是一个函数吗❓为什么可以去调用 listen
app虽然是一个函数,其实也是一个对象,故而可以去调用 listen
2.2 在createApplication中并没有发现app中有listen函数
app可以直接调用listen 这里有一段很重要的处理即:
1
mixin(app, proto, false); //底层做了混入处理
proto 本质是 application,在 application.js中其本质就是调用了 http.createServer(this).listen 把参数全部传递了过来; 依据:
1 2 3 4 5
app.listen = functionlisten() { var server = http.createServer(this); return server.listen.apply(server, arguments); };
3. app.use(中间件)内部发生了什么❓
open application.js 在 app.use = function use() 函数中生成了一个全局路由 router,在 var fns = flatten(slice.call(arguments, offset)) 做了扁平处理,将所有函数赋值给了 fns,接着通过 fns.forEach()取出每一个函数在228行本质调用了 router.use()函数