7stud
7stud

Reputation: 48589

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.

Upvotes: 44

Views: 31708

Answers (1)

mscdex
mscdex

Reputation: 106698

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

Upvotes: 35

Related Questions