Deltaxfx Deltaxfx - 1 year ago 88
Node.js Question with Express, how does express app know what port to listen on?

I am pretty new to nodejs and very new to and express. I have some code that is working, but am having trouble understanding exactly why it's working.

My question for the below code is how does the express app know to listen on port 80? There's a server.listen. But there is no app.listen in the code. Yet readily accepts posted data.

Please consider the following code

var https = require('https');
var url = require('url');
var fs = require('fs');
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
//var io = require('');
var zlib = require('zlib');

app.use(bodyParser.urlencoded({extended: true }));

var options = {
key: fs.readFileSync('my.key'),
cert: fs.readFileSync('my.crt')

var serverPort = 80;
var server = https.createServer(options, app);
var io = require('')(server);

// log when the server is ready
server.listen(serverPort, function() {
console.log('Web socket server up and running at port %s', serverPort);
// this prints 80, as expected
});'/api', function (req, res) {
// working code is in here that receives the post variables and responds

Answer Source

With Express, the app object is just a request handler for some http server. If you call app.listen(), then the app object will create an http server for you. But, if you have created your own http server (which your code example does), then the app object just becomes a request listener on that server with this line of your code:

var server = https.createServer(options, app);

That creates the http server and registers app as a request listener (so it sees all incoming requests). This allows the Express app object to then process the routes that are registered with it to server routes like app.get(...) or

And, the port for Express is the port for the http server so it's the port that was used when the http server was created. What's important to understand here is that Express is not its own server. It's just a request listener for some http server.

In your code example, your http server is set up for port 80 so that's the port being used and Express gets registered as a request handler on all those incoming http requests on that port.

If you look at the source code for app.listen(), you see this:

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

All, it does is create an http server with the app object as a listener and then call .listen() on that new server.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download