7stud 7stud - 5 months ago 70
Node.js Question

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

On the socket.io web page,

Get Started: Chat application
, located here:


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


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();

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();

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
?? The http docs are no help.


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