Home > node.js > Finding the hostname in node.js

Finding the hostname in node.js

This is a simple thing, but something I tend to forget and have to go find again. So here it is for later…

To get the OS hostname use the os module.
var hostname = require(“os”).hostname;
to just get the first piece of the name:
var hostname = require(‘os’).hostname().split(‘.’).shift();

Of course, only do it that way if you don’t otherwise need the os module. Otherwise require the os module and set it to a variable so you can reuse it without require each time.

To get the hostname for the current request, look in
request.headers.host

Categories: node.js
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment