Box9 Box9 - 4 months ago 11
Javascript Question

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

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


Express 4.x answer:

Express 4.x (per Tien Do's answer below), now treats app.listen() as an asynchronous operation, so listener.address() will only return data inside of app.listen()'s callback:

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

var listener = app.listen(8888, function(){
    console.log('Listening on port ' + listener.address().port); //Listening on port 8888

Express 3 answer:

I think you are looking for this(express specific?):

console.log("Express server listening on port %d", app.address().port)

You might have seen this(bottom line), when you create directory structure from express command:

alfred@alfred-laptop:~/node$ express test4
   create : test4
   create : test4/app.js
   create : test4/public/images
   create : test4/public/javascripts
   create : test4/logs
   create : test4/pids
   create : test4/public/stylesheets
   create : test4/public/stylesheets/style.less
   create : test4/views/partials
   create : test4/views/layout.jade
   create : test4/views/index.jade
   create : test4/test
   create : test4/test/app.test.js
alfred@alfred-laptop:~/node$ cat test4/app.js 

 * Module dependencies.

var express = require('express');

var app = module.exports = express.createServer();

// Configuration

  app.set('views', __dirname + '/views');
  app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] }));
  app.use(express.staticProvider(__dirname + '/public'));

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 

app.configure('production', function(){

// Routes

app.get('/', function(req, res){
  res.render('index.jade', {
    locals: {
        title: 'Express'

// Only listen on $ node app.js

if (!module.parent) {
  console.log("Express server listening on port %d", app.address().port)