Carlos Miguel Colanta Carlos Miguel Colanta - 5 months ago 8
Node.js Question

Why do some developer use 'http' and 'express' to create the server?

Particularly on this line of code:

I'm kinda new on node.js and most of the tutorials that I've seen initialize the server by

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

app = express();

//omit

http.createServer(app).listen(1337)


wherein, if you're already using
express
then you can just do :

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

// omit

app.listen(1337,function(){

});


Are there any major difference between those two code structures?

Answer

No meaningful difference. In fact, if you look at the code for app.listen(), all it does is do http.createServer() and than call .listen() on it. It's just meant to be a shortcut that saves you using the http module directly.

Here's the code for app.listen():

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

Your second code block is just a bit less code because it uses the app.listen() shortcut. Both do the same.