Back to Blog
Node.jsosSystemPlatform

Node.js os Module Guide

Master the Node.js os module for accessing operating system information and platform utilities.

B
Bootspring Team
Engineering
April 29, 2019
5 min read

The os module provides operating system utilities for accessing system information, CPU data, memory stats, and more. Here's how to use it.

Basic System Info#

1import os from 'node:os'; 2 3// Platform and architecture 4console.log('Platform:', os.platform()); // 'darwin', 'linux', 'win32' 5console.log('Architecture:', os.arch()); // 'x64', 'arm64' 6console.log('OS Type:', os.type()); // 'Darwin', 'Linux', 'Windows_NT' 7console.log('Release:', os.release()); // '21.6.0' 8console.log('Version:', os.version()); // 'Darwin Kernel Version 21.6.0' 9 10// Machine info 11console.log('Hostname:', os.hostname()); 12console.log('Home Dir:', os.homedir()); 13console.log('Temp Dir:', os.tmpdir());

CPU Information#

1import os from 'node:os'; 2 3// CPU cores 4const cpus = os.cpus(); 5console.log('CPU Cores:', cpus.length); 6console.log('CPU Model:', cpus[0].model); 7console.log('CPU Speed:', cpus[0].speed, 'MHz'); 8 9// Detailed CPU info 10cpus.forEach((cpu, index) => { 11 console.log(`Core ${index}:`, { 12 model: cpu.model, 13 speed: cpu.speed, 14 times: cpu.times, 15 }); 16}); 17 18// CPU usage calculation 19function getCPUUsage() { 20 const cpus = os.cpus(); 21 22 return cpus.map((cpu) => { 23 const total = Object.values(cpu.times).reduce((a, b) => a + b, 0); 24 const idle = cpu.times.idle; 25 return { 26 usage: ((total - idle) / total * 100).toFixed(2) + '%', 27 idle: (idle / total * 100).toFixed(2) + '%', 28 }; 29 }); 30}

Memory Information#

1import os from 'node:os'; 2 3// Memory in bytes 4const totalMem = os.totalmem(); 5const freeMem = os.freemem(); 6 7console.log('Total Memory:', formatBytes(totalMem)); 8console.log('Free Memory:', formatBytes(freeMem)); 9console.log('Used Memory:', formatBytes(totalMem - freeMem)); 10console.log('Memory Usage:', ((1 - freeMem / totalMem) * 100).toFixed(2) + '%'); 11 12function formatBytes(bytes) { 13 const units = ['B', 'KB', 'MB', 'GB', 'TB']; 14 let unitIndex = 0; 15 16 while (bytes >= 1024 && unitIndex < units.length - 1) { 17 bytes /= 1024; 18 unitIndex++; 19 } 20 21 return `${bytes.toFixed(2)} ${units[unitIndex]}`; 22}

Network Interfaces#

1import os from 'node:os'; 2 3const interfaces = os.networkInterfaces(); 4 5// List all interfaces 6for (const [name, addresses] of Object.entries(interfaces)) { 7 console.log(`\n${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 }); 13} 14 15// Get local IP address 16function getLocalIP() { 17 const interfaces = os.networkInterfaces(); 18 19 for (const addresses of Object.values(interfaces)) { 20 for (const addr of addresses) { 21 if (addr.family === 'IPv4' && !addr.internal) { 22 return addr.address; 23 } 24 } 25 } 26 27 return '127.0.0.1'; 28} 29 30console.log('Local IP:', getLocalIP());

User Information#

1import os from 'node:os'; 2 3// Current user info 4const userInfo = os.userInfo(); 5console.log('Username:', userInfo.username); 6console.log('Home Dir:', userInfo.homedir); 7console.log('Shell:', userInfo.shell); 8console.log('UID:', userInfo.uid); 9console.log('GID:', userInfo.gid); 10 11// With encoding option 12const userInfoBuffer = os.userInfo({ encoding: 'buffer' }); 13console.log('Username (buffer):', userInfoBuffer.username.toString());

System Uptime and Load#

1import os from 'node:os'; 2 3// System uptime 4const uptime = os.uptime(); 5console.log('Uptime:', formatUptime(uptime)); 6 7function formatUptime(seconds) { 8 const days = Math.floor(seconds / 86400); 9 const hours = Math.floor((seconds % 86400) / 3600); 10 const minutes = Math.floor((seconds % 3600) / 60); 11 const secs = Math.floor(seconds % 60); 12 13 return `${days}d ${hours}h ${minutes}m ${secs}s`; 14} 15 16// Load average (Unix only) 17const loadAvg = os.loadavg(); 18console.log('Load Average (1, 5, 15 min):', loadAvg); 19 20// Load as percentage of CPUs 21const cpuCount = os.cpus().length; 22console.log('Load % (1 min):', (loadAvg[0] / cpuCount * 100).toFixed(2) + '%');

Constants#

1import os from 'node:os'; 2 3// Signal constants 4console.log('SIGINT:', os.constants.signals.SIGINT); 5console.log('SIGTERM:', os.constants.signals.SIGTERM); 6console.log('SIGKILL:', os.constants.signals.SIGKILL); 7 8// Error constants 9console.log('ENOENT:', os.constants.errno.ENOENT); 10console.log('EACCES:', os.constants.errno.EACCES); 11console.log('EPERM:', os.constants.errno.EPERM); 12 13// Priority constants 14console.log('Priority Low:', os.constants.priority.PRIORITY_LOW); 15console.log('Priority Normal:', os.constants.priority.PRIORITY_NORMAL); 16console.log('Priority High:', os.constants.priority.PRIORITY_HIGH);

Process Priority#

1import os from 'node:os'; 2 3// Get current process priority 4const priority = os.getPriority(); 5console.log('Current Priority:', priority); 6 7// Set process priority (requires appropriate permissions) 8try { 9 os.setPriority(os.constants.priority.PRIORITY_LOW); 10 console.log('Priority set to low'); 11} catch (err) { 12 console.error('Could not set priority:', err.message); 13} 14 15// Set priority for specific PID 16try { 17 os.setPriority(process.pid, os.constants.priority.PRIORITY_NORMAL); 18} catch (err) { 19 console.error('Error:', err.message); 20}

System Monitor#

1import os from 'node:os'; 2 3class SystemMonitor { 4 constructor(interval = 5000) { 5 this.interval = interval; 6 this.history = []; 7 } 8 9 getStats() { 10 const cpus = os.cpus(); 11 const totalMem = os.totalmem(); 12 const freeMem = os.freemem(); 13 14 return { 15 timestamp: new Date(), 16 cpu: { 17 cores: cpus.length, 18 model: cpus[0].model, 19 loadAvg: os.loadavg(), 20 }, 21 memory: { 22 total: totalMem, 23 free: freeMem, 24 used: totalMem - freeMem, 25 usagePercent: ((1 - freeMem / totalMem) * 100).toFixed(2), 26 }, 27 uptime: os.uptime(), 28 platform: os.platform(), 29 hostname: os.hostname(), 30 }; 31 } 32 33 start(callback) { 34 this.timer = setInterval(() => { 35 const stats = this.getStats(); 36 this.history.push(stats); 37 38 // Keep last 100 entries 39 if (this.history.length > 100) { 40 this.history.shift(); 41 } 42 43 callback(stats); 44 }, this.interval); 45 } 46 47 stop() { 48 if (this.timer) { 49 clearInterval(this.timer); 50 } 51 } 52 53 getHistory() { 54 return this.history; 55 } 56} 57 58// Usage 59const monitor = new SystemMonitor(2000); 60 61monitor.start((stats) => { 62 console.clear(); 63 console.log('=== System Stats ==='); 64 console.log(`Memory: ${stats.memory.usagePercent}% used`); 65 console.log(`Load Avg: ${stats.cpu.loadAvg.map(l => l.toFixed(2)).join(', ')}`); 66 console.log(`Uptime: ${Math.floor(stats.uptime / 3600)} hours`); 67}); 68 69// Stop after 30 seconds 70setTimeout(() => monitor.stop(), 30000);

Cross-Platform Paths#

1import os from 'node:os'; 2import path from 'node:path'; 3 4// Platform-specific paths 5const homeDir = os.homedir(); 6const tempDir = os.tmpdir(); 7 8// Common directories 9const appDataDir = process.env.APPDATA || 10 (os.platform() === 'darwin' 11 ? path.join(homeDir, 'Library', 'Application Support') 12 : path.join(homeDir, '.config')); 13 14const cacheDir = process.env.XDG_CACHE_HOME || 15 (os.platform() === 'darwin' 16 ? path.join(homeDir, 'Library', 'Caches') 17 : path.join(homeDir, '.cache')); 18 19console.log('App Data:', appDataDir); 20console.log('Cache:', cacheDir); 21console.log('Temp:', tempDir); 22 23// EOL constant 24console.log('Line ending:', JSON.stringify(os.EOL)); 25// '\n' on Unix, '\r\n' on Windows

Best Practices#

Usage: ✓ Cache static values ✓ Handle platform differences ✓ Use constants for signals/errors ✓ Format bytes for display Performance: ✓ Avoid polling too frequently ✓ cpus() can be expensive ✓ Cache network interfaces ✓ Use async alternatives when available Cross-Platform: ✓ Check platform for platform-specific code ✓ Use path.join for file paths ✓ Handle missing features gracefully ✓ Use os.EOL for line endings Avoid: ✗ Assuming Unix-only features ✗ Ignoring permission errors ✗ Blocking with frequent calls ✗ Hardcoding platform values

Conclusion#

The os module provides essential system information for Node.js applications. Use it for monitoring resources, configuring platform-specific behavior, and accessing user information. Remember that some features like load average are Unix-specific, and always handle cross-platform differences gracefully. For performance monitoring, cache static values and avoid polling too frequently.

Share this article

Help spread the word about Bootspring