This may be a very basic question but I simply don't get it. What is the difference between creating an app using Express.js and starting the app listening on port 1234, for example:
var express = require('express');
var app = express();
//app.configure, app.use etc
app.listen(1234);
and adding an http server:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
//app.configure, app.use etc
server.listen(1234);
What's the difference?
If I navigate to http://localhost:1234
, thus I get the same output.
The app. listen() function is used to bind and listen the connections on the specified host and port. This method is identical to Node's http.
listen() (Express) will create a regular HTTP server (by using http. createServer() ); if you want to run Express over HTTPS, you need to use https.
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.
The listen() function applies only to stream sockets. It indicates a readiness to accept client connection requests, and creates a connection request queue of length backlog to queue incoming connection requests. Once full, additional connection requests are rejected. Parameter Description socket.
The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io
within the same HTTP server instance:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
...
server.listen(1234);
However, app.listen()
also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:
var express = require('express');
var app = express();
// app.use/routes/etc...
var server = app.listen(3033);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
...
});
There is one more difference of using the app and listening to http server is when you want to setup for https server
To setup for https, you need the code below:
var https = require('https');
var server = https.createServer(app).listen(config.port, function() {
console.log('Https App started');
});
The app from express will return http server only, you cannot set it in express, so you will need to use the https server command
var express = require('express');
var app = express();
app.listen(1234);
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