Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js' http.Server and http.createServer, what's the difference?

What is the difference between:

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

and

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

like image 465
wulfgarpro Avatar asked Dec 13 '12 10:12

wulfgarpro


People also ask

What is HTTP createServer NodeJS?

The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.

Is NodeJS an HTTP server?

The task of a web server is to open a file on the server and return the content to the client. Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP).

What is the difference between HTTP server and Express server?

HTTP is an independent module. Express is made on top of the HTTP module. HTTP module provides various tools (functions) to do things for networking like making a server, client, etc. Express along with what HTTP does provide many more functions in order to make development easy.


1 Answers

Based on the source code of nodejs (extract below), createServer is just a helper method to instantiate a Server.

Extract from line 1674 of http.js.

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

So therefore the only true difference in the two code snippets you've mentioned in your original question, is that you're not using the new keyword.


For clarity the Server constructor is as follows (at time of post - 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); 
like image 138
isNaN1247 Avatar answered Sep 24 '22 06:09

isNaN1247