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());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}%`);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.
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);Exercise: Node.js OS Module
What does `os.platform()` return?