NodeJS: How to get the server's port?

By : Box9

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?

By : Box9


The findandbind npm addresses this for express/restify/connect:

By : muckabout

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");

             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);

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

This video can help you solving your question :)
By: admin