Express.js - app.listen vs server.listen Express.js - app.listen vs server.listen express express

Express.js - app.listen vs server.listen


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);...server.listen(1234);

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();// app.use/routes/etc...var server    = app.listen(3033);var io        = require('socket.io').listen(server);io.sockets.on('connection', function (socket) {  ...});


There is one more difference of using the app and listening to http server is when you want to setup for https server

To setup for https, you need the code below:

var https = require('https');var server = https.createServer(app).listen(config.port, function() {    console.log('Https App started');});

The app from express will return http server only, you cannot set it in express, so you will need to use the https server command

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


Just for punctuality purpose and extend a bit Tim answer.
From official documentation:

The app returned by express() is in fact a JavaScript Function,DESIGNED TO BE PASSED to Node’s HTTP servers as a callback to handlerequests.

This makes it easy to provide both HTTP and HTTPS versions of yourapp with the same code base, as the app does not inherit from these(it is simply a callback):

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

The app.listen() method returns an http.Server object and (for HTTP)is a convenience method for the following:

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