NodeJS: How to get the server's port?

292,189

Solution 1

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.configure(function(){
  app.set('views', __dirname + '/views');
  app.use(express.bodyDecoder());
  app.use(express.methodOverride());
  app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] }));
  app.use(app.router);
  app.use(express.staticProvider(__dirname + '/public'));
});

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

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

// Routes

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

// Only listen on $ node app.js

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

Solution 2

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

Solution 3

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

Solution 4

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

Solution 5

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.

Share:
292,189

Related videos on Youtube

David Tang
Author by

David Tang

Reach me via reactaudit.com for personalised help. Follow me on Twitter: @Dvtng Check out: teamlinks.io

Updated on November 19, 2020

Comments

  • David Tang
    David Tang over 3 years

    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?

    • Andrew_1510
      Andrew_1510 over 8 years
      Find in req.headers.host
  • David Tang
    David Tang over 13 years
    Thanks, I think that's exactly what I'm looking for. I'll accept it as soon as I get a chance to test it. Cheers.
  • David Tang
    David Tang over 13 years
    +1 and thanks for the research. I'm accepting Alfred's answer since he found the exact thing I was looking for, but I'm glad I know it's not in the Node core now.
  • Mary Hamlin
    Mary Hamlin almost 12 years
    Or you could just use the old method of creating the server, which still works. There just seems to no longer be a way to access the port afterword. However, since you are specifying the port yourself in the call to server.listen, there really isn't a need to use server.address().port, since you can just use the same value that you passed into server.listen.
  • Mary Hamlin
    Mary Hamlin almost 12 years
    (Although I did just read the migration guide and see that the method for creating an app and server that you mentioned above is actually the new preferred method.)
  • Nate
    Nate over 11 years
    @MaryHamlin: This is useful if you are passing 0 to server.listen(), in which case a random port number is assigned. You might do this if you’re running several Express apps on one server and you don’t want to manually assign port numbers.
  • Vicary
    Vicary over 10 years
    app.listen() also returns the http server instance.
  • Tien Do
    Tien Do over 9 years
    But I don't know why server.address().address is always 0.0.0.0 on my local development machine (OSX).
  • RavenHursT
    RavenHursT over 8 years
    This should be added to the accepted answer since Express 4.0 no longer treats app.listen() as a synchronous operation and you need to run listener.address() in the callback now.
  • Andrei Stalbe
    Andrei Stalbe over 8 years
    And if you don't want to have that variable var listener you can use this.address().port inside app.listen() callback
  • Diogenes
    Diogenes almost 7 years
    What does this look like in Express 5.x?
  • Laxmana
    Laxmana almost 7 years
    Best answer so far! If you are using ES6 do not use arrow-functions. this will be undefined.
  • jlguenego
    jlguenego about 6 years
    You can also get the port anywhere in a middleware : req.socket.address().port
  • WORMSS
    WORMSS about 5 years
    Just to add on to what @AndreiStalbe said, you can use this.address.port() but you cannot use that inside an arrow function. you will need to do old school app.listen(8000, function () { console.log('http://localhost:' + this.address().port); } (yes, I know backticks are nicer, but I can't do them in stack overflow comments)
  • Ciro Santilli OurBigBook.com
    Ciro Santilli OurBigBook.com over 2 years
    listener.address doesn't work when I try to run it from inside an async function, not sure why. Express 4.17.1, Node v14.17.0.
  • Ciro Santilli OurBigBook.com
    Ciro Santilli OurBigBook.com over 2 years
    This works from inside an async function while listener.address().port approach didn't.
  • KARASZI István
    KARASZI István about 2 years
    This is the answer! :)