28

What is the difference between:

http.Server(function(req,res) {});

and

http.createServer(function(req, res) {});

4

2 回答 2

26

基于 nodejs 的源代码(摘录如下),createServer它只是一个帮助方法来实例化一个Server.

摘自http.js 的第 1674 行

exports.Server = Server;


exports.createServer = function(requestListener) {
  return new Server(requestListener);
};

因此,您在原始问题中提到的两个代码片段的唯一真正区别是您没有使用new关键字。


为清楚起见,Server构造函数如下(2012-12-13 后):

function Server(requestListener) {
  if (!(this instanceof Server)) return new Server(requestListener);
  net.Server.call(this, { allowHalfOpen: true });

  if (requestListener) {
    this.addListener('request', requestListener);
  }

  // Similar option to this. Too lazy to write my own docs.
  // http://www.squid-cache.org/Doc/config/half_closed_clients/
  // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F
  this.httpAllowHalfOpen = false;

  this.addListener('connection', connectionListener);

  this.addListener('clientError', function(err, conn) {
    conn.destroy(err);
  });
}
util.inherits(Server, net.Server);
于 2012-12-13T10:31:10.623 回答
2

根据文档,它似乎是

http.createServer = function (requestListener) {
     var ser = new http.Server();
     ser.addListener(requestListener);
     return ser;
};
于 2012-12-13T10:28:48.027 回答