Logo
Published on

How to get OS hostname in NodeJS? Intro to `os` module.

Authors
  • avatar
    Name
    Kamil Cieplicki
    Twitter

Welcome in 2023! This is a part of NodeJS tips and tricks.

How to get OS hostname in NodeJS?

To get the hostname of the current system in Node.js, you can use the os module from the standard library and call the hostname function. Here's an example:

import * as os from 'os';

console.log(os.hostname());

This will output the hostname of the system.

You can find more information about using os module in the NodeJS documentation. https://nodejs.org/api/os.html

NodeJS os module capabilities

The os module in Node.js provides a way to access various operating system-related functions and information. Here are some of the things you can do with the os module:

  • Get the operating system name: os.type()
  • Get the operating system platform: os.platform()
  • Get the operating system release: os.release()
  • Get the total amount of system memory: os.totalmem()
  • Get the amount of free system memory: os.freemem()
  • Get the system uptime: os.uptime()
  • Get the home directory of the current user: os.homedir()
  • Get the system's temporary directory: os.tmpdir()

Here's an example of how to use the os module to get some system information:

import * as os from 'os';

console.log(`Hostname: ${os.hostname()}`);
console.log(`Operating System: ${os.type()} ${os.platform()} ${os.release()}`);
console.log(`Total Memory: ${os.totalmem()}`);
console.log(`Free Memory: ${os.freemem()}`);
console.log(`Uptime: ${os.uptime()}`);
console.log(`Home Directory: ${os.homedir()}`);
console.log(`Temporary Directory: ${os.tmpdir()}`);