You often see example hello world code for Node that creates an Http Server, starts listening on a port, then followed by something along the lines of:
conso
In case when you need a port at the time of request handling and app is not available, you can use this:
request.socket.localPort
var express = require('express');
var app = express();
app.set('port', Config.port || 8881);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
Express server listening on port 8881
If you're using express, you can get it from the request object:
req.app.settings.port // => 8080 or whatever your app is listening at.
The easier way is just to call app.get('url'), which gives you the protocol, sub domain, domain, and port.
The findandbind npm addresses this for express/restify/connect: https://github.com/gyllstromk/node-find-and-bind
You might be looking for process.env.PORT. This allows you to dynamically set the listening port using what are called "environment variables". The Node.js code would look like this:
const port = process.env.PORT || 3000;
app.listen(port, () => {console.log(`Listening on port ${port}...`)});
You can even manually set the dynamic variable in the terminal using export PORT=5000, or whatever port you want.