美文网首页
Express源码解析(一)

Express源码解析(一)

作者: 东冬2086 | 来源:发表于2020-10-15 23:30 被阅读0次

每天学一点,分享我的所得。
Express算是nodejs最知名的框架了。即使nodejs掌握的不多,也能使用简单几条语句,轻松创建web服务器。如此便捷,那它是如何工作的呢,今天我们就来瞧一瞧(Version:4.17.1)。
首先,看一下express源码的结构。

中间件、路由、基于node的http模块封装的request和response、还有公用方法,一共只有11个文件,却实现的强大的功能,这代码质量,不得不佩服。按照我的思路一个个解析(看源码要细,慢慢理解
  1. express.js
    项目入口文件。先找导出部分
// 默认导出 createApplication函数
exports = module.exports = createApplication;

这里有一个知识点:exports和module.exports的区别和用法。简单说一下。module.exports和exports默认指向同一个地址一个空对象,module.exports为nodejs文件的默认导出。当module.exports指向了新的对象,则exports指向的地址对导出无效。上面这种写法,是将exports和module.exports进行强绑定。
接下来看这个导出函数

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函数给app对象添加属性,false不覆盖属性。proto这个文件里有很多方法都是app.xx的属性,之后以req和res为原型创建对象,并添加新属性app。暴漏出去。之后执行proto里面的init方法。返回app对象。
由此可见所有的秘密都在application.js文件里。

  1. application.js
    老规矩先找module.exports的位置
var app = exports = module.exports = {};

导出app对象,该对象上有express().xx全部的方法。按调用顺序,直接先看init方法。

相关文章

网友评论

      本文标题:Express源码解析(一)

      本文链接:https://www.haomeiwen.com/subject/dsgipktx.html