10

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?

Carlos Miguel Colanta
  • 2,685
  • 3
  • 31
  • 49
  • You don't even have to look at the code, as one answer suggests. You just have to read the [documentation](http://expressjs.com/en/4x/api.html), which says "Binds and listens for connections on the specified host and port. This method is **identical** to Node’s `http.Server.listen()`." –  Jul 04 '16 at 04:06

1 Answers1

12

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979