🌱BeginnerNode.js Foundations

The os Module

Query operating system information like CPU count, memory, hostname, and temp directory

Overview

The built-in `os` module exposes information about the operating system your Node.js process is running on. While most Node.js applications don't need to query OS details frequently, the module becomes invaluable when writing deployment scripts, monitoring tools, health-check endpoints, or when you need to make decisions based on the machine's resources β€” like how many worker threads to spawn. The most commonly used functions are `os.cpus()` which returns an array describing each logical CPU core (useful for setting worker thread counts), `os.totalmem()` and `os.freemem()` for memory statistics in bytes, and `os.hostname()` which returns the machine's network name. These three alone cover the majority of real-world use cases. The module also provides path utilities: `os.homedir()` gives the current user's home directory (equivalent to `~` in shell), and `os.tmpdir()` returns the OS-designated directory for temporary files β€” far more portable than hard-coding `/tmp`. When you need to create a temporary file, always use `os.tmpdir()` so your code works on Windows (where `C:\\Users\\User\\AppData\\Local\\Temp` is the temp dir) as well as Unix systems.

Key Points

  • β€’os.cpus() returns an array of CPU core info objects β€” its length is the number of logical cores available
  • β€’os.totalmem() and os.freemem() return memory in bytes; divide by 1024^3 to convert to GB
  • β€’os.hostname() returns the machine's network name β€” useful in logs and health-check responses
  • β€’os.platform() returns "linux", "darwin", "win32", etc. β€” use this for OS-specific code paths
  • β€’os.homedir() and os.tmpdir() give portable paths that work across operating systems
  • β€’os.EOL is the OS-specific end-of-line character (\n on Unix, \r\n on Windows)

Examples

Reading CPU and memory information

const os = require('os');

const cpus = os.cpus();
console.log('CPU model:', cpus[0].model);
console.log('Logical cores:', cpus.length);

const totalGB = (os.totalmem() / (1024 ** 3)).toFixed(2);
const freeGB  = (os.freemem()  / (1024 ** 3)).toFixed(2);
console.log(`Memory: ${freeGB} GB free of ${totalGB} GB total`);

cpus.length is the number of logical (hyperthreaded) cores, not physical ones. This is the value you use when choosing a default thread count.

Platform, architecture, and hostname

const os = require('os');

console.log('Platform:', os.platform()); // 'linux', 'darwin', 'win32'
console.log('Arch:', os.arch());         // 'x64', 'arm64', etc.
console.log('Hostname:', os.hostname());
console.log('OS release:', os.release());
console.log('Home dir:', os.homedir());
console.log('Temp dir:', os.tmpdir());

Choosing worker count based on CPU cores

const os = require('os');
const { Worker } = require('worker_threads');

const NUM_WORKERS = Math.max(1, os.cpus().length - 1);
console.log(`Spawning ${NUM_WORKERS} workers on ${os.cpus().length}-core machine`);

// Common pattern: leave one core for the event loop
for (let i = 0; i < NUM_WORKERS; i++) {
  // new Worker('./worker.js');
  console.log(`Would start worker ${i + 1}`);
}

Leaving one core for the main Node process prevents the OS from starving the event loop when all workers are busy.

Building a health-check payload with os info

const os = require('os');

function getHealthInfo() {
  return {
    hostname: os.hostname(),
    platform: os.platform(),
    arch: os.arch(),
    cpuCores: os.cpus().length,
    memoryTotalMB: Math.round(os.totalmem() / (1024 ** 2)),
    memoryFreeMB:  Math.round(os.freemem()  / (1024 ** 2)),
    uptime: os.uptime(), // seconds the OS has been running
    nodeUptime: process.uptime(), // seconds this Node process has been running
  };
}

console.log(JSON.stringify(getHealthInfo(), null, 2));

Common Mistakes

  • Hard-coding "/tmp" for temporary files β€” on Windows this path does not exist; use os.tmpdir() instead
  • Treating os.cpus().length as the number of physical CPU chips β€” it counts logical cores (includes hyperthreading)
  • Using os.freemem() to decide if an allocation will succeed β€” free memory fluctuates rapidly; check it only for informational logging
  • Comparing os.platform() === "unix" β€” the string is never "unix"; use "linux" or "darwin" for specific Unix variants

Note

os.networkInterfaces() returns all network interfaces and their IP addresses. Use it to build a health-check that reports which IP the server is listening on β€” much more debuggable than just showing a port number.

Exercises

Write Node.js code in your local terminal. Use the editor below to follow along, then mark each exercise as done once it works.

Loading editor…

Completed: 0 / 6 exercises

Knowledge Check

Question 1 of 4

What does os.cpus().length tell you?