下兔子洞 - “res”在express和/或nodejs中来自哪里

Down the rabbit hole - Where does "res" originate from in express and/or nodejs?

本文关键字:nodejs 兔子洞 res express      更新时间:2023-09-26

我试图更多地了解 express 和 nodejs 的内部结构。在 express' response.js 文件中查找,它经常将几种方法分配给res,这似乎是一个原型。

具体来说,res被声明为 res = http.ServerResponse.prototype .

好的,那么http是什么? http声明为 http = require('http')

因此,在快递http.js文件中,我们看到exports = module.exports = HTTPServer;

HTTPServer似乎是这种方法:

function HTTPServer(middleware){
  connect.HTTPServer.call(this, []);
  this.init(middleware);
};

这就是我陷入困境的地方。根据我的逻辑,似乎ServerResponse是在HTTPServer方法上调用的,这当然没有意义。因此,我一定错过了什么。

更新:

我刚刚意识到 express 创建了一个 HTTPServer 实例:

exports.createServer = function(options){
  if ('object' == typeof options) {
    return new HTTPSServer(options, Array.prototype.slice.call(arguments, 1));
  } else {
    return new HTTPServer(Array.prototype.slice.call(arguments));
  }
};
所以我猜是不是在这种情况下调用

ServerResponse?但是我仍然无法找到ServerResponse...

我在快速源文件中看不到任何http.js文件。

根据node.js http http = require('http')的文档将加载http模块,该模块具有ServerResponse对象。

因此,表达式代码通过其他方法增强了 ServerResponse 对象。