Node.js的http.Server和http.createServer有什么区别?

时间:2012-12-13 10:23:06

标签: javascript node.js

有什么区别:

  

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

  

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

2 个答案:

答案 0 :(得分:20)

基于nodejs的源代码(下面提取),createServer只是实例化Server的辅助方法。

摘自line 1674 of http.js

exports.Server = Server;


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

因此,您在原始问题中提到的两个代码段中唯一的 true 区别在于您没有使用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);

答案 1 :(得分:2)

根据the docs,似乎是

http.createServer = function (requestListener) {
     var ser = new http.Server();
     ser.addListener(requestListener);
     return ser;
};