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?

1
  • 1
    This might be relevant. Commented Jan 9, 2017 at 2:29

2 Answers 2

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' }

Sign up to request clarification or add additional context in comments.

Comments

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.