[javascript] NodeJS: How to get the server's port?

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:

console.log('Server is listening on port 8000');

But ideally you'd want this instead:

console.log('Server is listening on port ' + server.port);

How do I retrieve the port the server is currently listening on without storing the number in a variable prior to calling server.listen()?

I've seen this done before but I can't find it in the Node documentation. Maybe it's something specific to express?

This question is related to javascript node.js express port

The answer is


In the current version (v0.5.0-pre) the port seems to be available as a property on the server object, see http://nodejs.org/docs/v0.4.7/api/net.html#server.address

var server = http.createServer(function(req, res) {
    ...
}

server.listen(8088);
console.log(server.address());
console.log(server.address().address);
console.log(server.address().port);

outputs

{ address: '0.0.0.0', port: 8088 }
0.0.0.0
8088

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.

With latest node.js (v0.3.8-pre): I checked the documentation, inspected the server instance returned by http.createServer(), and read the source code of server.listen()...

Sadly, the port is only stored temporarily as a local variable and ends up as an argument in a call to process.binding('net').bind() which is a native method. I did not look further.

It seems that there is no better way than keeping a reference to the port value that you provided to server.listen().


I was asking myself this question too, then I came Express 4.x guide page to see this sample:

var server = app.listen(3000, function() {
   console.log('Listening on port %d', server.address().port);
});

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

I use this way Express 4:

app.listen(1337, function(){
  console.log('Express listening on port', this.address().port);
});

By using this I don't need to use a separate variable for the listener/server.


req.headers.host.split(':')[1]

The simplest way to convert from the old style to the new (Express 3.x) style is like this:

var server = app.listen(8080);
console.log('Listening on port: ' + server.address().port);

Pre 3.x it works like this:

/* This no longer works */
app.listen(8080);
console.log('Listening on port: ' + app.address().port);

below a simple http server and how to get the listening port

var http = require("http");
             function onRequest(request, response) {
               console.log("Request received.");
               response.writeHead(200, {"Content-Type": "text/plain"});
               response.write("Hello World");
               response.end();
             }

             var server =http.createServer(onRequest).listen(process.env.PORT, function(){
            console.log('Listening on port '); //Listening on port 8888
        });

then get the server port by using :

console.log('Express server started on port %s', server.address().port);

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.


Requiring the http module was never necessary.

An additional import of http is not necessary in Express 3 or 4. Assigning the result of listen() is enough.

var server = require('express')();

server.get('/', function(req, res) {
  res.send("Hello Foo!");
});

var listener = server.listen(3000);
console.log('Your friendly Express server, listening on port %s', listener.address().port);
// Your friendly Express server, listening on port 3000

Again, this is tested in Express 3.5.1 & 4.0.0. Importing http was never necessary. The listen method returns an http server object. https://github.com/visionmedia/express/blob/master/lib/application.js#L531


The findandbind npm addresses this for express/restify/connect: https://github.com/gyllstromk/node-find-and-bind


In express v3.0,

/* No longer valid */
var app = express.createServer();
app.listen();
console.log('Server running on %s', app.address().port);

no longer works! For Express v3.0, you should create an app and a server this way:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000);
console.log('Express server started on port %s', server.address().port);

I ran in to this issue myself and wanted to document the new syntax. This and other changes in Express v3.0 are visible at https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x


If you did not define the port number and you want to know on which port it is running.

let http = require('http');
let _http = http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello..!')
}).listen();
console.log(_http.address().port);

FYI, every time it will run in a different port.


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


The easier way is just to call app.get('url'), which gives you the protocol, sub domain, domain, and port.


You can get the port number by using server.address().port like in below code:

var http = require('http');
var serverFunction = function (req, res) {

    if (req.url == '/') {
        console.log('get method');
        res.writeHead(200, { 'content-type': 'text/plain' });
        res.end('Hello World');
    }

}
var server = http.createServer(serverFunction);
server.listen(3002, function () {
    console.log('server is listening on port:', server.address().port);
});

const express = require('express');                                                                                                                           
const morgan = require('morgan')
const PORT = 3000;

morgan.token('port', (req) => { 
    return req.app.locals.port; 
});

const app = express();
app.locals.port = PORT;
app.use(morgan(':method :url :port'))
app.get('/app', function(req, res) {
    res.send("Hello world from server");
});

app1.listen(PORT);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to port

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated How do I kill the process currently using a port on localhost in Windows? Node.js Port 3000 already in use but it actually isn't? Can't connect to Postgresql on port 5432 Spring Boot - How to get the running port Make docker use IPv4 for port binding How to change the default port of mysql from 3306 to 3360 Open firewall port on CentOS 7 Unable to launch the IIS Express Web server, Failed to register URL, Access is denied XAMPP Port 80 in use by "Unable to open process" with PID 4