Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Server Hostname

Ok, so it seems pretty easy in Node.js to get the hostname of the request being made to my server:

app.get('/', function(req,res){
    console.log(req.headers.host);
});

Is there an easy way to determine the hostname of my actual http server? For example, my server is running at the address http://localhost:3000 - can I programatically determine this address? I am using expressjs.

like image 468
Craig Myles Avatar asked Sep 24 '12 09:09

Craig Myles


People also ask

How do I find the hostname of a node js server?

To get the name or hostname of the OS, you can use the hostname() method from the os module in Node. js. /* Get hostname of os in Node. js */ // import os module const os = require("os"); // get host name const hostName = os.

What server does node js use?

Node. js is a Javascript run-time environment built on Chrome's V8 Javascript engine. It comes with a http module that provides a set of functions and classes for building a HTTP server. For this basic HTTP server, we will also be using file system, path and url, all of which are native Node.

Does node js have a server?

Node. js is an open source server environment. Node. js uses JavaScript on the server.


1 Answers

Yes you can using the;

var express = require('express'),
    app = express(),
    server  = require('http').createServer(app);

server.listen(3000, function(err) {
        console.log(err, server.address());
});

should print

{ address: '0.0.0.0', family: 'IPv4', port: 3000 }

you can also retreive the hostname for the os by the following;

require('os').hostname();
like image 85
Jason Brumwell Avatar answered Oct 21 '22 19:10

Jason Brumwell