Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 836
Carlos Miguel Colanta Avatar asked Jul 04 '16 02:07

Carlos Miguel Colanta


People also ask

What is the difference between HTTP server and Express server?

HTTP is an independent module. Express is made on top of the HTTP module. HTTP module provides various tools (functions) to do things for networking like making a server, client, etc. Express along with what HTTP does provide many more functions in order to make development easy.

Do you need HTTP for Express?

Express does not have the ability to create a properly configured https server for you automatically. @user3497437 - I added more to my answer to show you two examples that are identical in function. You would typically only need to use http.

What is an HTTP server Express?

Express is a minimal and flexible Node. js web application framework that provides a robust set of features for web and mobile applications. In this article you'll learn how to create a http server using Express and other basics that you need to know about it.

Why should you separate Express APP and server?

Faster testing execution. Getting wider coverage metrics of the code. Allows deploying the same API under flexible and different network conditions. Better separation of concerns and cleaner code.


1 Answers

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.

like image 197
jfriend00 Avatar answered Oct 22 '22 23:10

jfriend00