NodeJS: How to get the server port?

You often see the hello world code example for Node that creates an Http server, starts listening on a port, and then something follows line by line:

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

But ideally, you would like this:

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

How to get the port that the server is currently listening to without storing the number in a variable before calling server.listen() ?

I have seen this before but cannot find it in the Node documentation. Maybe this is something specific to express?

+80
javascript express
Jan 30 '11 at 3:00
source share
17 answers

Express 4.x answer:

Express 4.x (for each Tien Do answer below) now treats app.listen () as an asynchronous operation, so listener.address () will only return data inside the app.listen () 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 may have seen this (bottom line) when you create the directory structure from the 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) } 
+81
Jan 30 '11 at 12:28
source share

In express v3.0,

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

does not work any more! For Express v3.0, you must create the application and server as follows:

 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 myself ran into this problem and wanted to document a 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

+61
Jul 19 2018-12-12T00:
source share

In the current version (v0.5.0-pre), the port appears to be available as a property of 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); 

exits

 { address: '0.0.0.0', port: 8088 } 0.0.0.0 8088 
+17
May 12 '11 at 12:57
source share

If you use express, you can get it from the request object:

 req.app.settings.port // => 8080 or whatever your app is listening at. 
+15
Oct 21 '12 at 8:25
source share

If you need a port during request processing and the application is not available, you can use this:

 request.socket.localPort 
+10
Feb 25 '14 at 2:36
source share

The requirement that the http module is never needed.

Additional http imports are not required in Express 3 or 4. Assigning a listen() result is sufficient.

 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 and 4.0.0. Import http never needed. The listen method returns an HTTP server object. https://github.com/visionmedia/express/blob/master/lib/application.js#L531

+8
Apr 15 '14 at 5:29
source share

I use this Express 4 method:

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

Using this, I do not need to use a separate variable for the listener / server.

+6
Mar 16 '15 at 11:25
source share

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

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

There seems to be no better way than storing a link to the port value that you provided the .listen () server.

+5
Jan 30 2018-11-11T00:
source share

The easiest way to convert from the old style to the new (Express 3.x) style is as follows:

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

Pre 3.x works as follows:

 /* This no longer works */ app.listen(8080); console.log('Listening on port: ' + app.address().port); 
+4
Mar 12 '14 at 15:03
source share
 req.headers.host.split(':')[1] 
+3
Jun 22 '16 at 1:42 on
source share

I also asked myself this question, then I came to the Express 4.x Page to see this example:

 var server = app.listen(3000, function() { console.log('Listening on port %d', server.address().port); }); 
+1
Oct 02 '14 at 6:18
source share

The port number can be obtained using server.address().port as shown below:

 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); }); 
+1
Apr 04 '17 at 6:50
source share
 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

+1
Apr 04 '17 at 8:00
source share

findandbind npm addresses this for expression / recovery / connection: https://github.com/gyllstromk/node-find-and-bind

0
Dec 12 '13 at 13:53 on
source share

below a simple http server and how to get a 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 using:

 console.log('Express server started on port %s', server.address().port); 
0
Sep 14 '16 at 22:05
source share
 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); 
0
Jul 13 '17 at 13:39 on
source share

A simpler way is to call app.get('url') , which provides you with the protocol, subdomain, domain and port.

-one
Sep 16 '16 at 12:53 on
source share



All Articles