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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With