Tamas Tamas - 1 year ago 593
Node.js Question

Express.js - app.listen vs server.listen

This may be a very basic question but I simply don't get it. What is the difference between creating an app using Express.js and starting the app listening on port 1234 for example:

var express = require('express');
var app = express();

//app.configure, app.use etc


and adding an http server:

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

//app.configure, app.use etc


What's the difference? If I navigate to
- I get the same output...

Answer Source

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();
var socketio  = require('socket.io');

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download