Node.js OS Module

The built-in os module gives Node.js scripts information about the operating system and hardware they're running on, from CPU details to memory and user directories.

Importing the os Module

The os module is part of Node's standard library, so it requires no installation. It exposes a mix of methods and read-only properties that describe the current machine.

Basic os module usage

const os = require('os');

console.log('Platform:', os.platform());
console.log('Architecture:', os.arch());
console.log('Hostname:', os.hostname());

Identifying the Platform

os.platform() returns a short string identifying the operating system, such as 'win32' for Windows, 'darwin' for macOS, or 'linux' for Linux distributions. This is useful for writing cross-platform scripts that need to branch on OS-specific behavior, such as path separators or shell commands.

Branching logic based on platform

const os = require('os');

function getShellCommand() {
  switch (os.platform()) {
    case 'win32':
      return 'dir';
    case 'darwin':
    case 'linux':
      return 'ls -la';
    default:
      throw new Error(`Unsupported platform: ${os.platform()}`);
  }
}

console.log('Command to run:', getShellCommand());
Note: Prefer checking os.platform() over parsing process.version or guessing from file paths — it's the documented, stable way to detect the OS.

Inspecting CPU Information

os.cpus() returns an array with one entry per logical CPU core, each containing the model name, clock speed in MHz, and time spent in different CPU states (user, nice, sys, idle, irq). This is commonly used to size worker pools or thread counts based on available hardware.

Reading CPU core count and model

const os = require('os');

const cpus = os.cpus();
console.log('Number of logical cores:', cpus.length);
console.log('CPU model:', cpus[0].model);
console.log('Clock speed (MHz):', cpus[0].speed);

Checking Memory

os.totalmem() and os.freemem() both return byte counts describing the machine's total installed RAM and currently available RAM. Dividing by 1024 three times converts bytes to gigabytes for human-readable output.

Reporting memory usage as a percentage

const os = require('os');

function bytesToGB(bytes) {
  return (bytes / (1024 ** 3)).toFixed(2);
}

const total = os.totalmem();
const free = os.freemem();
const usedPercent = (((total - free) / total) * 100).toFixed(1);

console.log(`Total memory: ${bytesToGB(total)} GB`);
console.log(`Free memory: ${bytesToGB(free)} GB`);
console.log(`Memory in use: ${usedPercent}%`);
Note: os.freemem() reflects the whole system's free memory, not just what your Node process is using. For per-process memory, use process.memoryUsage() instead.

User and Directory Information

os.homedir() returns the current user's home directory path, and os.tmpdir() returns the operating system's default directory for temporary files — both are cross-platform, so you never need to hardcode paths like /home/user or C:\Users\name.

MethodReturnsExample value (Linux)
os.platform()Operating system identifier'linux'
os.homedir()Current user's home directory'/home/alice'
os.tmpdir()Default temp file directory'/tmp'
os.freemem()Free memory in bytes4294967296

Building a path inside the home directory

const os = require('os');
const path = require('path');

const configPath = path.join(os.homedir(), '.myapp', 'config.json');
console.log('Config will be stored at:', configPath);
Note: Combining os.homedir() with the path module (rather than string concatenation) keeps your code working correctly on both Windows and POSIX systems, since they use different path separators.

Exercise: Node.js OS Module

What does `os.platform()` return?