The os module answers questions about the machine your Node.js process is actually running on — its platform, its available memory, its CPU details. It's read-only: you can ask the operating system about itself, but os doesn't let you change any of it.
Basic system information
const os = require('os');
console.log('Platform:', os.platform()); // 'linux', 'darwin', 'win32'
console.log('Architecture:', os.arch()); // 'x64', 'arm64'
console.log('Hostname:', os.hostname());
console.log('OS release:', os.release());
console.log('Home directory:', os.homedir());
console.log('Temp directory:', os.tmpdir());
Memory
const totalGB = (os.totalmem() / 1024 / 1024 / 1024).toFixed(2);
const freeGB = (os.freemem() / 1024 / 1024 / 1024).toFixed(2);
console.log(`Memory: ${freeGB} GB free of ${totalGB} GB total`);
Both values come back in bytes, so dividing by 1024 three times converts to gigabytes for a more readable output.
CPU details
const cpus = os.cpus();
console.log(`This machine has ${cpus.length} logical CPU cores`);
console.log('First core model:', cpus[0].model);
os.cpus() returns an array — one entry per logical core — each with its clock speed and time spent in different states (user, system, idle). Knowing cpus.length matters directly when deciding how many worker processes to run, covered on the next page.
A practical use: a lightweight health-check endpoint
const os = require('os');
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
uptimeSeconds: os.uptime(),
freeMemoryMB: Math.round(os.freemem() / 1024 / 1024),
loadAverage: os.loadavg() // [1min, 5min, 15min] — Linux/macOS only, returns zeros on Windows
}));
}
}).listen(3000);
A real monitoring system checking this endpoint can catch a server that's running dangerously low on memory or under heavy sustained load, before it actually crashes or becomes unresponsive.
Why this matters beyond curiosity
Knowing details about the host machine lets your application make smarter runtime decisions — scaling worker processes to match available CPU cores, warning when memory runs low, or adjusting behavior based on the platform it's deployed on. It's less about any single method and more about giving your code environmental awareness it wouldn't otherwise have.