The os Module
Query operating system information like CPU count, memory, hostname, and temp directory
Overview
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.
Completed: 0 / 6 exercises
Knowledge Check
Question 1 of 4