Search code examples
node.jshttpexpresslisten

node http and express listening difference


I am new to node and express. I have come across two ways of creating an express app that listens on a specific TCP port which, as far as I can tell, yield the same result. Could someone please shed some light to the difference to these, if there are any... It's the listen function

Method 1 - using the express module only:

var express = require('express');

var port = 8080;
var app = express();
app.set('port', port);
...
// different listen method
app.listen(app.get('port'), function(){ 
  console.log('now listening on port ' + app.get('port'));
});

Method 2 - using the express and http modules:

var http = require('http'), 
    express = require('express');

var port = 8080;
var app = express();
app.set('port', port);
...
// different listen method
http.createServer(app).listen(app.get('port'), function(){ 
  console.log('now listening on port ' + app.get('port'));
});

Solution

  • Take a look at the definition of app.listen in the express source code: https://github.com/visionmedia/express/blob/9e6b881f8566f26f2d2ea017657455ec7c674ad6/lib/application.js#L524-L548

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

    It is just a convenience method for doing what you've defined in "Method 2" above. (Here's how apply() works if you need a refresher.)

    So, they do the same thing :)