44

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.

1 Answer 1

35

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

1
  • 3
    Okay, I would prefer to type Server() instead of createServer(), so that's what I'll do. Plus I'll save a function call. Thanks.
    – 7stud
    Nov 14, 2014 at 1:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.