Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http.createServer(app) v. http.Server(app)

On the socket.io web page, Get Started: Chat application, located here:

http://socket.io/get-started/chat/

there is this code:

var app = require('express')(); var http = require('http').Server(app); 

which could be rewritten a little more clearly like this:

var express = require('express'); var http = require('http');  var app = express(); var server = http.Server(app); 

The socket.io example uses http.Server() to create a server. Yet, the express docs for app.listen() show an example where the server is created using http.createServer(app):

app.listen()
Bind and listen for connections on the given host and port. This method is identical to node's http.Server#listen().

var express = require('express');   var app = express();   app.listen(3000); 

The app returned by express() is in fact a JavaScript Function, designed to be passed to node's HTTP servers as a callback to handle requests. This allows you to provide both HTTP and HTTPS versions of your app with the same codebase easily, as the app does not inherit from these (it is simply a callback):

var express = require('express'); var https = require('https'); var http = require('http'); var app = express();  http.createServer(app).listen(80); https.createServer(options, app).listen(443); 

The app.listen() method is a convenience method for the following (if you wish to use HTTPS or provide both, use the technique above):

app.listen = function(){   var server = http.createServer(this);   return server.listen.apply(server, arguments); }; 

What's the difference between http.createServer(app) and http.Server(app)?? The http docs are no help.

like image 548
7stud Avatar asked Nov 14 '14 00:11

7stud


People also ask

What is HTTP createServer?

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.

How do I get the HTTP server from the Express App?

The usual two ways to start a server for use with Express are this: var express = require('express'); var app = express(); // Express creates a server for you and starts it var server = app. listen(80);

Is Express an HTTP server?

The Express philosophy is to provide small, robust tooling for HTTP servers, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs. Navigate to the port 3000 as previously set in the server.


1 Answers

There is no difference. http.createServer() only does one thing: it calls http.Server() internally and returns the resulting instance.

like image 65
mscdex Avatar answered Oct 09 '22 08:10

mscdex