Node Server Port

How do you log you Node.js server port number?

Let’s say you use Node.js and start a server with:

server.listen(1337, function(){
  console.info('Server listening on port ' + 1337);
});

Or maybe you use Express.js and something similar to this:

server.listen(app.get('port'), function(){
  console.info('Server listening on port ' + app.get('port'));
});

It works. However, the better way is to use:

this.address().port

For example, for Node.js server:

server.listen(1337, function(){
  console.info('Server listening on port ' + this.address().port);
});

This way you get the real port number which in some weird edge cases might be different from the number that you supplied to listen.

You can also use this style:

server.listen(app.get('port'), function(){
  console.info('Server listening on port ' + server.address().port);
});

PS: You can still get advantage of the 50% super early bird ticket price for the live in-person Node.js training on March 28-29 in San Francisco, CA.

Author: Azat

Techies, entrepreneur, 20+ years in tech/IT/software/web development expert: NodeJS, JavaScript, MongoDB, Ruby on Rails, PHP, SQL, HTML, CSS. 500 Startups (batch Fall 2011) alumnus. http://azat.co http://github.com/azat-co

2 thoughts on “Node Server Port”

  1. Hi Azat,
    I hope you will be good and doing really interesting stuff. Today i checked your course at udemy about “Node Program: From 0 to Hero with Nodejs, MongoDB&Expressjs “. I am really searching this course from long time. I want to attend this course but unable to pay you 200$ for this course now . Is there any chance you will start promo on this course as you start at some other courses hosted at udemy?

    Now a days i am really working hard to learn the Nodejs,Expressjs and coffee script. And i know your course will boost my learning curve hundred times.

    Thanks your for your work and effort for learners.

    Waiting to hear some kind from you.

    Best Regards

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.