Back to Blog
Node.jsOSSystemPerformance

Node.js OS Module Guide

Master the Node.js os module. From system info to CPU details to memory management.

B
Bootspring Team
Engineering
May 17, 2020
6 min read

The os module provides operating system information and utilities. Here's how to use it.

Basic System Information#

1const os = require('os'); 2 3// Operating system 4console.log('Platform:', os.platform()); // 'darwin', 'win32', 'linux' 5console.log('OS Type:', os.type()); // 'Darwin', 'Windows_NT', 'Linux' 6console.log('Release:', os.release()); // '20.6.0' 7console.log('Version:', os.version()); // 'Darwin Kernel Version 20.6.0' 8console.log('Architecture:', os.arch()); // 'x64', 'arm64' 9 10// Machine info 11console.log('Hostname:', os.hostname()); // 'my-macbook' 12console.log('Home Dir:', os.homedir()); // '/Users/username' 13console.log('Temp Dir:', os.tmpdir()); // '/tmp' 14 15// User info 16const userInfo = os.userInfo(); 17console.log('Username:', userInfo.username); 18console.log('UID:', userInfo.uid); 19console.log('GID:', userInfo.gid); 20console.log('Shell:', userInfo.shell); 21console.log('Home:', userInfo.homedir);

CPU Information#

1const os = require('os'); 2 3// CPU cores 4const cpus = os.cpus(); 5console.log('CPU Count:', cpus.length); 6 7// CPU details 8cpus.forEach((cpu, index) => { 9 console.log(`CPU ${index}:`); 10 console.log(` Model: ${cpu.model}`); 11 console.log(` Speed: ${cpu.speed} MHz`); 12 console.log(` Times:`, cpu.times); 13}); 14 15// CPU usage calculation 16function getCPUUsage() { 17 const cpus = os.cpus(); 18 let totalIdle = 0; 19 let totalTick = 0; 20 21 cpus.forEach((cpu) => { 22 for (const type in cpu.times) { 23 totalTick += cpu.times[type]; 24 } 25 totalIdle += cpu.times.idle; 26 }); 27 28 return { 29 idle: totalIdle / cpus.length, 30 total: totalTick / cpus.length, 31 usage: 100 - (100 * totalIdle / totalTick), 32 }; 33} 34 35// Monitor CPU usage over time 36function monitorCPU(interval = 1000) { 37 let previousUsage = getCPUUsage(); 38 39 setInterval(() => { 40 const currentUsage = getCPUUsage(); 41 const idleDiff = currentUsage.idle - previousUsage.idle; 42 const totalDiff = currentUsage.total - previousUsage.total; 43 const cpuPercent = 100 - (100 * idleDiff / totalDiff); 44 45 console.log(`CPU Usage: ${cpuPercent.toFixed(2)}%`); 46 previousUsage = currentUsage; 47 }, interval); 48}

Memory Information#

1const os = require('os'); 2 3// Total and free memory 4console.log('Total Memory:', os.totalmem()); 5console.log('Free Memory:', os.freemem()); 6 7// Human readable 8function formatBytes(bytes) { 9 const units = ['B', 'KB', 'MB', 'GB', 'TB']; 10 let index = 0; 11 let size = bytes; 12 13 while (size >= 1024 && index < units.length - 1) { 14 size /= 1024; 15 index++; 16 } 17 18 return `${size.toFixed(2)} ${units[index]}`; 19} 20 21console.log('Total:', formatBytes(os.totalmem())); // "16.00 GB" 22console.log('Free:', formatBytes(os.freemem())); // "4.23 GB" 23 24// Memory usage percentage 25function getMemoryUsage() { 26 const total = os.totalmem(); 27 const free = os.freemem(); 28 const used = total - free; 29 30 return { 31 total, 32 free, 33 used, 34 percentage: (used / total) * 100, 35 }; 36} 37 38const memory = getMemoryUsage(); 39console.log(`Memory: ${memory.percentage.toFixed(2)}% used`); 40 41// Process memory (from process module) 42const processMemory = process.memoryUsage(); 43console.log('Process Memory:'); 44console.log(' RSS:', formatBytes(processMemory.rss)); 45console.log(' Heap Total:', formatBytes(processMemory.heapTotal)); 46console.log(' Heap Used:', formatBytes(processMemory.heapUsed)); 47console.log(' External:', formatBytes(processMemory.external));

Network Interfaces#

1const os = require('os'); 2 3// Get all network interfaces 4const interfaces = os.networkInterfaces(); 5 6for (const [name, addresses] of Object.entries(interfaces)) { 7 console.log(`Interface: ${name}`); 8 addresses.forEach((addr) => { 9 console.log(` ${addr.family}: ${addr.address}`); 10 console.log(` MAC: ${addr.mac}`); 11 console.log(` Internal: ${addr.internal}`); 12 console.log(` Netmask: ${addr.netmask}`); 13 console.log('---'); 14 }); 15} 16 17// Get local IP address 18function getLocalIP() { 19 const interfaces = os.networkInterfaces(); 20 21 for (const addresses of Object.values(interfaces)) { 22 for (const addr of addresses) { 23 if (addr.family === 'IPv4' && !addr.internal) { 24 return addr.address; 25 } 26 } 27 } 28 29 return '127.0.0.1'; 30} 31 32console.log('Local IP:', getLocalIP()); 33 34// Get all non-internal IPv4 addresses 35function getAllLocalIPs() { 36 const interfaces = os.networkInterfaces(); 37 const ips = []; 38 39 for (const addresses of Object.values(interfaces)) { 40 for (const addr of addresses) { 41 if (addr.family === 'IPv4' && !addr.internal) { 42 ips.push(addr.address); 43 } 44 } 45 } 46 47 return ips; 48}

System Uptime and Load#

1const os = require('os'); 2 3// System uptime in seconds 4const uptime = os.uptime(); 5console.log('Uptime:', uptime, 'seconds'); 6 7// Format uptime 8function formatUptime(seconds) { 9 const days = Math.floor(seconds / 86400); 10 const hours = Math.floor((seconds % 86400) / 3600); 11 const minutes = Math.floor((seconds % 3600) / 60); 12 13 const parts = []; 14 if (days > 0) parts.push(`${days}d`); 15 if (hours > 0) parts.push(`${hours}h`); 16 if (minutes > 0) parts.push(`${minutes}m`); 17 18 return parts.join(' ') || '< 1m'; 19} 20 21console.log('Uptime:', formatUptime(os.uptime())); // "5d 12h 34m" 22 23// Load average (Unix only) 24const loadAvg = os.loadavg(); 25console.log('Load Average (1m, 5m, 15m):', loadAvg); 26// [1.5, 1.2, 0.9] 27 28// Load percentage based on CPU count 29const cpuCount = os.cpus().length; 30console.log('Load %:', loadAvg.map(load => 31 `${((load / cpuCount) * 100).toFixed(1)}%` 32));

System Constants#

1const os = require('os'); 2 3// End of line character 4console.log('EOL:', JSON.stringify(os.EOL)); 5// '\n' on Unix, '\r\n' on Windows 6 7// Priority constants 8console.log('Priority Levels:'); 9console.log(' PRIORITY_LOW:', os.constants.priority.PRIORITY_LOW); 10console.log(' PRIORITY_BELOW_NORMAL:', os.constants.priority.PRIORITY_BELOW_NORMAL); 11console.log(' PRIORITY_NORMAL:', os.constants.priority.PRIORITY_NORMAL); 12console.log(' PRIORITY_ABOVE_NORMAL:', os.constants.priority.PRIORITY_ABOVE_NORMAL); 13console.log(' PRIORITY_HIGH:', os.constants.priority.PRIORITY_HIGH); 14console.log(' PRIORITY_HIGHEST:', os.constants.priority.PRIORITY_HIGHEST); 15 16// Signal constants 17console.log('Signals:', os.constants.signals); 18// { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, ... } 19 20// Error constants 21console.log('Error codes:', os.constants.errno); 22// { E2BIG: 7, EACCES: 13, EADDRINUSE: 48, ... }

Process Priority#

1const os = require('os'); 2 3// Get process priority 4const pid = process.pid; 5const priority = os.getPriority(pid); 6console.log('Current priority:', priority); 7 8// Set process priority 9try { 10 os.setPriority(pid, os.constants.priority.PRIORITY_HIGH); 11 console.log('Priority set to HIGH'); 12} catch (err) { 13 console.error('Failed to set priority:', err.message); 14} 15 16// Priority for another process 17function getProcessPriority(pid) { 18 try { 19 return os.getPriority(pid); 20 } catch { 21 return null; 22 } 23}

System Health Check#

1const os = require('os'); 2 3function getSystemHealth() { 4 const cpus = os.cpus(); 5 const totalMemory = os.totalmem(); 6 const freeMemory = os.freemem(); 7 const loadAvg = os.loadavg(); 8 9 return { 10 platform: os.platform(), 11 arch: os.arch(), 12 hostname: os.hostname(), 13 uptime: formatUptime(os.uptime()), 14 cpu: { 15 model: cpus[0].model, 16 cores: cpus.length, 17 loadAverage: { 18 '1m': loadAvg[0].toFixed(2), 19 '5m': loadAvg[1].toFixed(2), 20 '15m': loadAvg[2].toFixed(2), 21 }, 22 }, 23 memory: { 24 total: formatBytes(totalMemory), 25 free: formatBytes(freeMemory), 26 used: formatBytes(totalMemory - freeMemory), 27 usagePercent: ((1 - freeMemory / totalMemory) * 100).toFixed(2) + '%', 28 }, 29 network: getLocalIP(), 30 }; 31} 32 33console.log(JSON.stringify(getSystemHealth(), null, 2));

Monitoring Service#

1const os = require('os'); 2const EventEmitter = require('events'); 3 4class SystemMonitor extends EventEmitter { 5 constructor(options = {}) { 6 super(); 7 this.interval = options.interval || 5000; 8 this.memoryThreshold = options.memoryThreshold || 90; 9 this.cpuThreshold = options.cpuThreshold || 80; 10 this.previousCPU = null; 11 this.timer = null; 12 } 13 14 start() { 15 this.previousCPU = this.getCPUInfo(); 16 this.timer = setInterval(() => this.check(), this.interval); 17 this.emit('started'); 18 } 19 20 stop() { 21 if (this.timer) { 22 clearInterval(this.timer); 23 this.timer = null; 24 this.emit('stopped'); 25 } 26 } 27 28 getCPUInfo() { 29 const cpus = os.cpus(); 30 let idle = 0; 31 let total = 0; 32 33 cpus.forEach(cpu => { 34 for (const type in cpu.times) { 35 total += cpu.times[type]; 36 } 37 idle += cpu.times.idle; 38 }); 39 40 return { idle, total }; 41 } 42 43 check() { 44 // Memory check 45 const memoryUsage = (1 - os.freemem() / os.totalmem()) * 100; 46 if (memoryUsage > this.memoryThreshold) { 47 this.emit('memoryWarning', { usage: memoryUsage }); 48 } 49 50 // CPU check 51 const currentCPU = this.getCPUInfo(); 52 const idleDiff = currentCPU.idle - this.previousCPU.idle; 53 const totalDiff = currentCPU.total - this.previousCPU.total; 54 const cpuUsage = 100 - (100 * idleDiff / totalDiff); 55 56 if (cpuUsage > this.cpuThreshold) { 57 this.emit('cpuWarning', { usage: cpuUsage }); 58 } 59 60 this.previousCPU = currentCPU; 61 this.emit('stats', { memory: memoryUsage, cpu: cpuUsage }); 62 } 63} 64 65// Usage 66const monitor = new SystemMonitor({ interval: 2000 }); 67 68monitor.on('memoryWarning', ({ usage }) => { 69 console.log(`Memory warning: ${usage.toFixed(2)}%`); 70}); 71 72monitor.on('cpuWarning', ({ usage }) => { 73 console.log(`CPU warning: ${usage.toFixed(2)}%`); 74}); 75 76monitor.start();

Best Practices#

Information Gathering: ✓ Cache static values (platform, arch) ✓ Format values for readability ✓ Handle cross-platform differences ✓ Use appropriate units Monitoring: ✓ Sample CPU over time intervals ✓ Set appropriate thresholds ✓ Log warnings and anomalies ✓ Consider system load in decisions Performance: ✓ Don't poll too frequently ✓ Cache when appropriate ✓ Use events for notifications ✓ Consider worker threads for heavy monitoring Avoid: ✗ Assuming specific OS behavior ✗ Ignoring platform differences ✗ Blocking the event loop ✗ Excessive system calls

Conclusion#

The os module provides essential system information for monitoring, diagnostics, and platform-aware code. Use it to gather CPU, memory, and network details, monitor system health, and adapt behavior based on the operating system.

Share this article

Help spread the word about Bootspring