1

Here is my code:

var http = require('http');

function onRequest(req, res) {
    // do something
}

var server = http.createServer(onRequest);
server.listen(8000);
console.log("The server is now running on " + <<server.address>>);

I want the <> to be something like "http://localhost:8000". How do I do that?

user3685285
  • 6,066
  • 13
  • 54
  • 95
  • 1
    [This](http://stackoverflow.com/questions/33853695/node-js-server-address-address-returns) might be relevant. – snanda Jan 09 '17 at 02:29

2 Answers2

3
var http = require('http');
var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080);
console.log('Server listening:', `http://${server.address().address}:${server.address().port}`);

I think you can use

server.address()#

Added in: v0.1.90 Returns the bound address, the address family name, and port of the server as reported by the operating system. Useful to find which port was assigned when getting an OS-assigned address. Returns an object with port, family, and address properties: { port: 12346, family: 'IPv4', address: '127.0.0.1' }

BlackMamba
  • 10,054
  • 7
  • 44
  • 67
1

This should give you your hostname and port on server startup:

var server  = require('http').createServer(onRequest);
var port = '8000';
server.listen(port, function(err) {
    console.log(err, require('os').hostname()+':'+port);
});
Konstantin Kreft
  • 613
  • 5
  • 18