Advanced cross-platform operating system monitoring utilities with TypeScript support
npm install node-os-utils[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]



๐ Version 2.0 - A complete rewrite of the popular Node.js operating system monitoring library.
Modern, TypeScript-native, cross-platform system monitoring library providing comprehensive system information with intelligent caching, event-driven monitoring, and robust error handling.
> Breaking Changes: This is a major version release with breaking changes from v1.x.
bootTime & uptimeSeconds, and Linux process metrics include precise startTimegetSupportedPlatforms() and checkPlatformCapabilities()./bin/bash โ /bin/sh, PowerShell auto discovery) and uniform error objects./proc, macOS via sysctl/powermetrics, Windows via PowerShell + WMI) while reporting declared feature support.| Capability | Linux | macOS | Windows |
|------------|:-----:|:-----:|:-------:|
| CPU usage / info | โ
| โ
| โ
|
| CPU temperature | โ ๏ธ Needs /sys/class/thermal | โ ๏ธ Requires powermetrics (sudo) | โ (no public API) |
| Memory pressure | โ ๏ธ Partially available | โ
| โ ๏ธ Estimated via WMI |
| Disk IO stats | โ
| โ
| โ |
| Network stats | โ
(/proc/net/dev) | โ
(netstat -ib) | โ ๏ธ Admin rights for PowerShell |
| Process details | โ
| โ
| โ
(WMI) |
| System services | โ ๏ธ systemctl when available | โ | โ
|
| Container awareness | โ ๏ธ Detects containers, gracefully degrades | โ ๏ธ Detects containers, limited | โ ๏ธ Detects containers, limited |
> Legend: โ Fully supported ยท โ ๏ธ Partially limited ยท โ Not supported
``ts
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils();
const report = await osutils.checkPlatformCapabilities();
console.table({
platform: report.platform,
supported: report.supported,
commands: report.capabilities.commands.join(','),
features: report.capabilities.features.join(',')
});
if (!report.supported) {
console.warn('โ Some metrics are unavailable:', report.issues);
}
`
AdapterFactory.getDebugInfo() is also available when you need to inspect feature flags or confirm that platform-specific commands can be executed.
When running inside containers, the library automatically:
- detects Docker/Podman/Kubernetes via .dockerenv, /proc/1/cgroup, or env vars;systemctl
- disables service inspection () for non-systemd environments;ss
- falls back from to netstat and from ip to ifconfig when tooling is missing;adapter.getSupportedFeatures()
- returns rich error details so that callers can differentiate permission issues from unsupported features;
- keeps feature flags in sync via so monitors can short-circuit unsupported actions.
`bash`
npm install node-os-utils
Requirements:
- Node.js 18.0.0 or higher
- Supported OS: Linux, macOS, Windows
`typescript
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils();
// Get CPU usage
const cpuUsage = await osutils.cpu.usage();
if (cpuUsage.success) {
console.log('CPU Usage:', cpuUsage.data + '%');
}
// Get memory information
const memInfo = await osutils.memory.info();
if (memInfo.success) {
console.log('Memory:', memInfo.data);
}
// Get system overview
const overview = await osutils.overview();
console.log('System Overview:', overview);
`
`javascript
const { OSUtils } = require('node-os-utils');
const osutils = new OSUtils();
osutils.cpu.usage().then(result => {
if (result.success) {
console.log('CPU Usage:', result.data + '%');
}
});
`
`javascript
// Alternative instantiation method
const { createOSUtils } = require('node-os-utils');
const osutils = createOSUtils({
cacheEnabled: true,
cacheTTL: 10000
});
// Same API as OSUtils class
const cpuUsage = await osutils.cpu.usage();
`
`typescript
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils({
// Cache settings
cacheEnabled: true,
cacheTTL: 5000,
maxCacheSize: 1000,
// Execution settings
timeout: 10000,
// Debug mode
debug: false,
// Monitor-specific configurations
cpu: { cacheTTL: 30000 },
memory: { cacheTTL: 5000 },
disk: { cacheTTL: 60000 }
});
`
`typescript
// Configure individual monitors
const cpuMonitor = osutils.cpu
.withCaching(true, 30000)
.withConfig({ timeout: 5000 });
// Configure cache at runtime
osutils.configureCache({
enabled: true,
maxSize: 2000,
defaultTTL: 10000
});
`
All operations return a MonitorResult object for consistent error handling:
`typescript`
type MonitorResult
| {
success: true;
data: T;
timestamp: number;
cached: boolean;
platform: string;
}
| {
success: false;
error: MonitorError;
platform: string;
timestamp: number;
};
`typescript
const result = await osutils.cpu.info();
if (result.success) {
// Success: use result.data
console.log('CPU Model:', result.data.model);
console.log('Cores:', result.data.cores);
} else {
// Error: handle gracefully
console.error('Error:', result.error?.message);
console.error('Code:', result.error?.code);
// Platform-specific handling
if (result.error?.code === ErrorCode.PLATFORM_NOT_SUPPORTED) {
console.log('This feature is not available on', result.platform);
}
}
`
`typescript`
enum ErrorCode {
PLATFORM_NOT_SUPPORTED = 'PLATFORM_NOT_SUPPORTED', // Feature unavailable on current platform
COMMAND_FAILED = 'COMMAND_FAILED', // Shell/command execution failed
PARSE_ERROR = 'PARSE_ERROR', // Failed to parse command output or data
PERMISSION_DENIED = 'PERMISSION_DENIED', // Lacking required privileges
TIMEOUT = 'TIMEOUT', // Operation exceeded the configured timeout
INVALID_CONFIG = 'INVALID_CONFIG', // Provided configuration is invalid
NOT_AVAILABLE = 'NOT_AVAILABLE', // Metric temporarily unavailable
FILE_NOT_FOUND = 'FILE_NOT_FOUND', // Required file or path missing
NETWORK_ERROR = 'NETWORK_ERROR' // Network operation failed
}
- macOS temperature metrics rely on powermetrics and require administrator privileges (sudo powermetrics -n 1 -i 1000 --samplers smc). When unavailable, the adapter raises PLATFORM_NOT_SUPPORTED for that feature.Get-NetAdapterStatistics
- Windows network & process metrics call PowerShell CIM cmdlets (, Get-CimInstance). Run the host app in an elevated PowerShell session if you encounter PERMISSION_DENIED or COMMAND_FAILED errors./proc
- Linux command fallbacks: metrics primarily read . If utilities such as ip/ss are missing, the adapter retries with ifconfig/netstat, but you can confirm availability up front via osutils.checkPlatformCapabilities().MonitorResult.error.code
- Always inspect for structured error feedback (timeout, permission, unsupported) and provide user guidance accordingly.
Comprehensive CPU monitoring with real-time capabilities.
`typescript
// Basic CPU information
const cpuInfo = await osutils.cpu.info();
if (cpuInfo.success) {
console.log('Model:', cpuInfo.data.model);
console.log('Cores:', cpuInfo.data.cores);
console.log('Architecture:', cpuInfo.data.architecture);
}
// CPU usage monitoring
const cpuUsage = await osutils.cpu.usage();
if (cpuUsage.success) {
console.log('CPU Usage:', cpuUsage.data + '%');
}
// Detailed usage (overall + per core)
const usageDetails = await osutils.cpu.usageDetailed();
if (usageDetails.success) {
console.log('Overall:', usageDetails.data.overall);
console.log('Per core:', usageDetails.data.cores);
}
// Load average (Linux/macOS)
const loadAvg = await osutils.cpu.loadAverage();
if (loadAvg.success) {
console.log('Load Average:', loadAvg.data);
}
`
#### CPU Methods
| Method | Return Type | Description | Platform Support |
|--------|-------------|-------------|------------------|
| info() | Promise | CPU model, cores, threads, architecture | โ
All |usage()
| | Promise | CPU usage percentage (0-100) | โ
All |usageDetailed()
| | Promise | Usage breakdown including per-core data | โ
All |usageByCore()
| | Promise | Per-core usage percentages | โ
All |loadAverage()
| | Promise | Load averages (1, 5, 15 min) | โ
Linux/macOS |temperature()
| | Promise | CPU temperature sensors | โ ๏ธ Limited |frequency()
| | Promise | Current CPU frequencies | โ ๏ธ Limited |getCacheInfo()
| | Promise | CPU cache hierarchy information | โ ๏ธ Limited |coreCount()
| | Promise | Physical/logical core counts | โ
All |
#### Real-time CPU Monitoring
`typescriptCPU Usage: ${result.data.toFixed(2)}%
// Poll usage every second with manual interval control
const pollInterval = setInterval(async () => {
const result = await osutils.cpu.usage();
if (result.success) {
console.log();
if (result.data > 80) {
console.warn('โ ๏ธ High CPU usage detected!');
}
}
}, 1000);
setTimeout(() => {
clearInterval(pollInterval);
console.log('CPU usage polling stopped');
}, 30000);
// Fetch CPU info periodically using the built-in monitor helper
const cpuInfoSubscription = osutils.cpu.withCaching(false).monitor(5000, (info) => {
console.log('CPU Model:', info.model);
});
setTimeout(() => cpuInfoSubscription.unsubscribe(), 20000);
`
Detailed memory information with smart unit conversion.
`typescript
// Memory information with DataSize helpers
const memInfo = await osutils.memory.info();
if (memInfo.success) {
console.log('Total Memory:', memInfo.data.total.toGB().toFixed(2) + ' GB');
console.log('Available:', memInfo.data.available.toGB().toFixed(2) + ' GB');
console.log('Used:', memInfo.data.used.toGB().toFixed(2) + ' GB');
console.log('Usage:', memInfo.data.usagePercentage.toFixed(2) + '%');
}
// Quick memory usage percentage
const memUsage = await osutils.memory.usage();
if (memUsage.success) {
console.log('Memory Usage:', memUsage.data.toFixed(2) + '%');
}
// Summary view with formatted strings
const memSummary = await osutils.memory.summary();
if (memSummary.success) {
console.log('Summary:', memSummary.data);
}
`
#### Memory Methods
| Method | Return Type | Description | Platform Support |
|--------|-------------|-------------|------------------|
| info() | Promise | Detailed memory breakdown with DataSize objects | โ
All |detailed()
| | Promise | Adds platform-specific breakdown data | โ ๏ธ Platform |usage()
| | Promise | Memory usage percentage (0-100) | โ
All |available()
| | Promise | Available memory amount | โ
All |swap()
| | Promise | Virtual memory/swap information | โ
All |pressure()
| | Promise | Memory pressure indicators | โ ๏ธ Limited |summary()
| | Promise | Readable summary including swap usage | โ
All |
#### DataSize Object
`typescript
class DataSize {
constructor(bytes: number);
toBytes(): number;
toKB(): number;
toMB(): number;
toGB(): number;
toTB(): number;
toString(unit?: 'auto' | 'B' | 'KB' | 'MB' | 'GB' | 'TB'): string;
}
// Usage example
const memory = await osutils.memory.info();
if (memory.success) {
console.log(memory.data.total.toString('GB')); // "16.00 GB"
console.log(memory.data.available.toString()); // automatic unit selection
}
`
Comprehensive disk and storage monitoring.
`typescript
// All disk information
const diskInfo = await osutils.disk.info();
if (diskInfo.success) {
diskInfo.data.forEach(disk => {
console.log('Filesystem:', disk.filesystem);
console.log('Mount Point:', disk.mountpoint);
console.log('Total:', disk.total.toString('GB'));
console.log('Available:', disk.available.toString('GB'));
console.log('Usage:', disk.usagePercentage + '%');
});
}
// Specific mount usage
const rootUsage = await osutils.disk.usageByMountPoint('/');
if (rootUsage.success && rootUsage.data) {
console.log('Root usage:', rootUsage.data.usagePercentage + '%');
}
// I/O statistics
const ioStats = await osutils.disk.stats();
if (ioStats.success) {
ioStats.data.forEach(stat => {
console.log(${stat.device}:, {`
readBytes: stat.readBytes.toString('MB'),
writeBytes: stat.writeBytes.toString('MB'),
readCount: stat.readCount,
writeCount: stat.writeCount
});
});
}
#### Disk Methods
| Method | Return Type | Description | Platform Support |
|--------|-------------|-------------|------------------|
| info() | Promise | Disk/partition information | โ
All |infoByDevice(device)
| | Promise | Lookup device or mountpoint | โ
All |usage()
| | Promise | Usage for mounted filesystems | โ
All |usageByMountPoint(mountPoint)
| | Promise | Usage for a specific mount point | โ
All |overallUsage()
| | Promise | Weighted average usage across all disks | โ
All |stats()
| | Promise | I/O statistics summary (requires includeStats) | โ ๏ธ Limited |mounts()
| | Promise | Mount configuration details | โ
All |filesystems()
| | Promise | Available filesystem types | โ
All |spaceOverview()
| | Promise | Aggregate space usage | โ
All |healthCheck()
| | Promise | Basic disk health | โ ๏ธ Limited |
Network interface and traffic monitoring.
`typescript
// Network interfaces
const interfaces = await osutils.network.interfaces();
if (interfaces.success) {
interfaces.data.forEach(iface => {
console.log('Interface:', iface.name);
console.log('Addresses:', iface.addresses);
console.log('State:', iface.state);
});
}
// Network overview
const overview = await osutils.network.overview();
if (overview.success) {
console.log('Total RX:', overview.data.totalRxBytes.toString('MB'));
console.log('Total TX:', overview.data.totalTxBytes.toString('MB'));
}
// Per-interface statistics
const stats = await osutils.network.statsAsync();
if (stats.success) {
stats.data.forEach(stat => {
console.log(${stat.interface}: RX ${stat.rxBytes.toString('MB')} | TX ${stat.txBytes.toString('MB')});
});
}
// Real-time interface monitoring (returns NetworkInterface[] snapshots)
const netSub = osutils.network.monitor(5000, (interfacesSnapshot) => {
console.log('Active interfaces:', interfacesSnapshot.filter(iface => iface.state === 'up').map(iface => iface.name));
});
`
#### Network Methods
| Method | Return Type | Description | Platform Support |
|--------|-------------|-------------|------------------|
| interfaces() | Promise | All network interfaces | โ
All |interfaceByName(name)
| | Promise | Single interface lookup | โ
All |overview()
| | Promise | Aggregate link counters | โ
All |statsAsync()
| | Promise | Interface statistics (requires includeInterfaceStats) | โ
All |statsByInterface(name)
| | Promise | Stats for a specific interface | โ
All |bandwidth()
| | Promise | Calculated throughput over an interval | โ ๏ธ Limited |connections()
| | Promise | Active connections (requires includeConnections) | โ ๏ธ Limited |gateway()
| | Promise | Default gateway info | โ
All |publicIP()
| | Promise | Cached public IP lookup (placeholder) | โ ๏ธ Limited |healthCheck()
| | Promise | Network health summary | โ ๏ธ Limited |
Process management and monitoring capabilities.
`typescript
// List all processes
const processes = await osutils.process.list();
if (processes.success) {
console.log('Total processes:', processes.data.length);
// Show top 5 CPU consumers
const topCpu = processes.data
.filter(proc => proc.cpuUsage > 0)
.sort((a, b) => b.cpuUsage - a.cpuUsage)
.slice(0, 5);
topCpu.forEach(proc => {
console.log(${proc.name} (${proc.pid}): ${proc.cpuUsage.toFixed(2)}% CPU);
});
}
// Find specific processes
const nodeProcesses = await osutils.process.byName('node');
if (nodeProcesses.success) {
console.log('Node.js processes:', nodeProcesses.data.length);
}
// Current process info
const currentProc = await osutils.process.byPid(process.pid);
if (currentProc.success && currentProc.data) {
console.log('Current process memory:', currentProc.data.memoryUsage.toString('MB'));
}
`
#### Process Methods
| Method | Return Type | Description | Platform Support |
|--------|-------------|-------------|------------------|
| list(options?) | Promise | All running processes (optional filters) | โ
All |byPid(pid)
| | Promise | Specific process details | โ
All |byName(name)
| | Promise | Find by process name | โ
All |topByCpu(limit?)
| | Promise | Top CPU consumers | โ
All |topByMemory(limit?)
| | Promise | Top memory consumers | โ
All |children(parentPid)
| | Promise | Child processes (requires config) | โ ๏ธ Limited |tree(rootPid?)
| | Promise | Process hierarchy | โ ๏ธ Limited |stats()
| | Promise | Aggregate process statistics | โ
All |kill(pid, signal?)
| | Promise | Terminate process | โ ๏ธ Limited |
General system information and health monitoring.
`typescript
// System information
const sysInfo = await osutils.system.info();
if (sysInfo.success) {
console.log('Hostname:', sysInfo.data.hostname);
console.log('Platform:', sysInfo.data.platform);
console.log('Distro:', sysInfo.data.distro);
console.log('Release:', sysInfo.data.release);
console.log('Architecture:', sysInfo.data.arch);
}
// System uptime
const uptime = await osutils.system.uptime();
if (uptime.success) {
console.log('Uptime (ms):', uptime.data.uptime);
console.log('Boot time:', new Date(uptime.data.bootTime).toISOString());
console.log('Friendly uptime:', uptime.data.uptimeFormatted);
}
// Active users
const users = await osutils.system.users();
if (users.success) {
console.log('Logged users:', users.data.map(u => u.username));
}
`
#### System Methods
| Method | Return Type | Description | Platform Support |
|--------|-------------|-------------|------------------|
| info() | Promise | Complete system information | โ
All |uptime()
| | Promise | Uptime and derived timestamps | โ
All |load()
| | Promise | Load averages and health status | โ ๏ธ Limited |users()
| | Promise | Currently logged users | โ ๏ธ Platform |services()
| | Promise | Service status (requires config) | โ ๏ธ Limited |overview()
| | Promise | Synthetic summary | โ ๏ธ Limited |time()
| | Promise | Current system time metadata | โ
All |healthCheck()
| | Promise | System health overview | โ ๏ธ Limited |
| Platform | CPU | Memory | Disk | Network | Process | System | Notes |
|----------|-----|--------|------|---------|---------|--------|-------|
| Linux | โ
| โ
| โ
| โ
| โ
| โ
| Full support, optimized |
| macOS | โ
| โ
| โ
| โ
| โ
| โ
| Full support |
| Windows | โ
| โ
| โ
| โ ๏ธ | โ ๏ธ | โ
| Limited network & process |
Legend:
- โ
Full Support: All features available and tested
- โ ๏ธ Partial Support: Core features work, some limitations
- โ Not Supported: Feature not available
#### Linux
- Uses /proc filesystem for optimal performance
- Full support for all monitoring features
- Advanced I/O statistics available
- Temperature monitoring on supported hardware
#### macOS
- Uses system commands (top, vm_stat, df, etc.)
- Full feature compatibility
- Darwin-specific optimizations
- Integrated with macOS system APIs
#### Windows
- Uses PowerShell and WMI where available
- Network monitoring has some limitations
- Process tree functionality limited
- Core features fully supported
`typescript
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils({ debug: true });
// Comprehensive system overview
const overview = await osutils.overview();
console.log('๐ System Overview:');
if (overview.cpu.usage != null) {
console.log('CPU Usage:', overview.cpu.usage + '%');
}
if (overview.memory?.usagePercentage != null) {
console.log('Memory Usage:', overview.memory.usagePercentage + '%');
}
if (overview.disk?.usagePercentage != null) {
console.log('Disk Usage:', overview.disk.usagePercentage + '%');
}
if (overview.network) {
console.log('Network RX:', overview.network.totalRxBytes.toString('MB'));
console.log('Network TX:', overview.network.totalTxBytes.toString('MB'));
}
if (overview.processes) {
console.log('Processes:', overview.processes.total);
}
if (overview.system?.uptime != null) {
console.log('Uptime:', (overview.system.uptime / 3600).toFixed(1) + ' hours');
}
// System health check
const health = await osutils.healthCheck();
console.log('๐ฅ System Health:', health.status); // 'healthy' | 'warning' | 'critical'
if (health.issues.length > 0) {
console.log('โ ๏ธ Issues detected:');
health.issues.forEach(issue => console.log(- ${issue}));`
}
`typescript
// Create monitoring dashboard
class SystemDashboard {
private intervals: NodeJS.Timeout[] = [];
private alerts: string[] = [];
start() {
console.log('๐ Starting system monitoring dashboard...');
// CPU usage polling
this.intervals.push(setInterval(async () => {
const result = await osutils.cpu.usage();
if (result.success) {
const value = result.data.toFixed(2);
this.updateDisplay('CPU', ${value}%);โ ๏ธ High CPU usage: ${value}%
if (result.data > 80) {
this.addAlert();
}
}
}, 1000));
// Memory usage polling
this.intervals.push(setInterval(async () => {
const result = await osutils.memory.info();
if (result.success) {
const percent = result.data.usagePercentage;
this.updateDisplay('Memory', ${percent.toFixed(2)}%);โ ๏ธ High memory usage: ${percent.toFixed(2)}%
if (percent > 85) {
this.addAlert();
}
}
}, 2000));
// Disk usage polling
this.intervals.push(setInterval(async () => {
const result = await osutils.disk.usageByMountPoint('/');
if (result.success && result.data) {
this.updateDisplay('Disk', ${result.data.usagePercentage.toFixed(1)}%);โ ๏ธ Disk almost full: ${result.data.usagePercentage.toFixed(1)}%
if (result.data.usagePercentage > 90) {
this.addAlert();
}
}
}, 10000));
// Network statistics polling
this.intervals.push(setInterval(async () => {
const stats = await osutils.network.statsAsync();
if (stats.success) {
const aggregate = stats.data.reduce(
(acc, item) => ({
rx: acc.rx + item.rxBytes.toBytes(),
tx: acc.tx + item.txBytes.toBytes()
}),
{ rx: 0, tx: 0 }
);
this.updateDisplay(
'Network',
โ${(aggregate.rx / 1024 / 1024).toFixed(2)} MB โ${(aggregate.tx / 1024 / 1024).toFixed(2)} MB
);
}
}, 5000));
// Alert checker
this.intervals.push(setInterval(() => {
if (this.alerts.length > 0) {
console.log('๐จ Active Alerts:');
this.alerts.forEach(alert => console.log(alert));
this.alerts = [];
}
}, 10000));
}
private updateDisplay(metric: string, value: string) {
// Update your UI here
console.log(๐ ${metric}: ${value});
}
private addAlert(alert: string) {
this.alerts.push(alert);
}
stop() {
this.intervals.forEach(interval => clearInterval(interval));
this.intervals = [];
console.log('โน๏ธ Monitoring stopped');
}
}
// Usage
const dashboard = new SystemDashboard();
dashboard.start();
// Stop after 5 minutes
setTimeout(() => dashboard.stop(), 5 60 1000);
`
`typescript
// Performance-optimized configuration
const osutils = new OSUtils({
// Global cache settings
cacheEnabled: true,
cacheTTL: 5000,
maxCacheSize: 1000,
// Execution settings
timeout: 15000,
// Debug mode
debug: false,
// Monitor-specific settings
cpu: {
cacheTTL: 1000, // Fast refresh for CPU
interval: 100 // High precision monitoring
},
memory: {
cacheTTL: 5000 // Moderate refresh for memory
},
disk: {
cacheTTL: 30000, // Slow refresh for disk
timeout: 10000
},
network: {
cacheTTL: 2000, // Medium refresh for network
includeInterfaceStats: true
},
process: {
cacheTTL: 10000 // Slow refresh for processes
}
});
// Runtime cache configuration
osutils.configureCache({
enabled: true,
maxSize: 2000,
defaultTTL: 8000
});
// Cache statistics
const cacheStats = osutils.getCacheStats();
if (cacheStats) {
console.log('Cache hit rate:', cacheStats.hitRate.toFixed(1) + '%');
console.log('Cache entries:', cacheStats.size);
console.log('Estimated memory used:', (cacheStats.memoryUsage / (1024 * 1024)).toFixed(2) + ' MB');
}
// Clear cache when needed
osutils.clearCache();
`
`typescript
import { ErrorCode, MonitorError } from 'node-os-utils';
// Comprehensive error handling
class SystemMonitoringService {
private osutils: OSUtils;
constructor() {
this.osutils = new OSUtils({ debug: true });
}
async getSystemInfo() {
try {
const results = await Promise.allSettled([
this.osutils.cpu.info(),
this.osutils.memory.info(),
this.osutils.disk.info(),
this.osutils.network.interfaces(),
this.osutils.system.info()
]);
const data: Record
const errors: Array<{ component: string; error: MonitorError | Error; timestamp: Date }> = [];
results.forEach((result, index) => {
const keys = ['cpu', 'memory', 'disk', 'network', 'system'];
const key = keys[index];
if (result.status === 'fulfilled' && result.value.success) {
data[key] = result.value.data;
} else {
const monitorError = result.status === 'fulfilled'
? result.value.error
: (result.reason instanceof MonitorError
? result.reason
: MonitorError.createCommandFailed(process.platform, 'unknown', { reason: result.reason }));
errors.push({
component: key,
error: monitorError,
timestamp: new Date()
});
// Handle specific error types
this.handleComponentError(key, monitorError);
}
});
return { data, errors };
} catch (error) {
console.error('System monitoring failed:', error);
throw error;
}
}
private handleComponentError(component: string, error: any) {
switch (error?.code) {
case ErrorCode.PLATFORM_NOT_SUPPORTED:
console.warn(${component} monitoring not supported on ${process.platform});Insufficient permissions for ${component} monitoring
break;
case ErrorCode.PERMISSION_DENIED:
console.error();${component} monitoring timed out, retrying...
break;
case ErrorCode.TIMEOUT:
console.warn();${component} system command failed:
break;
case ErrorCode.COMMAND_FAILED:
console.error(, error.message);Unknown ${component} error:
break;
default:
console.error(, error?.message);
}
}
// Graceful degradation example
async getCPUUsageWithFallback(): Promise
const result = await this.osutils.cpu.usage();
if (result.success) {
return result.data;
}
// Fallback to OS module
const os = require('os');
const cpus = os.cpus();
// Simple calculation as fallback
return Math.random() * 20 + 10; // Mock fallback
}
}
`
Version 2.0 introduces several breaking changes for improved type safety and consistency:
#### 1. Constructor Changes
`typescript
// v1.x
const osu = require('node-os-utils');
const cpuUsage = await osu.cpu.usage();
// v2.0
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils();
const cpuResult = await osutils.cpu.usage();
if (cpuResult.success) {
const cpuUsage = cpuResult.data;
}
`
#### 2. Return Value Changes
`typescript
// v1.x - Direct values
const cpuUsage = await osu.cpu.usage(); // number
const memInfo = await osu.mem.info(); // object
// v2.0 - MonitorResult wrapper
const cpuResult = await osutils.cpu.usage();
if (cpuResult.success) {
const cpuUsage = cpuResult.data; // number
}
const memResult = await osutils.memory.info();
if (memResult.success) {
const memInfo = memResult.data; // MemoryInfo
}
`
#### 3. Module Name Changes
| v1.x | v2.0 |
|------|------|
| cpu | cpu (unchanged) |mem
| | memory |drive
| | disk |netstat
| | network |proc
| | process |os
| | system |
#### 4. Method Name Changes
| v1.x | v2.0 |
|------|------|
| osu.cpu.usage() | osutils.cpu.usage() |osu.mem.info()
| | osutils.memory.info() |osu.drive.info()
| | osutils.disk.info() |osu.netstat.inOut()
| | osutils.network.overview() |osu.proc.totalProcesses()
| | osutils.process.list().then(r => r.data.length) |
`typescript
// v1.x code
const osu = require('node-os-utils');
async function getSystemInfo() {
const cpuUsage = await osu.cpu.usage();
const memInfo = await osu.mem.info();
const driveInfo = await osu.drive.info();
return {
cpu: cpuUsage,
memory: memInfo,
disk: driveInfo
};
}
// v2.0 equivalent
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils();
async function getSystemInfo() {
const [cpuResult, memResult, diskResult] = await Promise.all([
osutils.cpu.usage(),
osutils.memory.info(),
osutils.disk.info()
]);
return {
cpu: cpuResult.success ? cpuResult.data : null,
memory: memResult.success ? memResult.data : null,
disk: diskResult.success ? diskResult.data : null
};
}
`
- [ ] Update import statements to use OSUtils classnew OSUtils()
- [ ] Add constructor call: MonitorResult
- [ ] Update all method calls to handle return typemem
- [ ] Change module names: โ memory, drive โ disk, etc.
- [ ] Add error handling for failed operations
- [ ] Update TypeScript types if using TypeScript
- [ ] Test all functionality after migration
`bashClone the repository
git clone https://github.com/SunilWang/node-os-utils.git
cd node-os-utils
$3
Available Test Scripts:
`bash
Core test suites
npm test # All tests
npm run test:unit # Unit tests only
npm run test:integration # Integration tests only
npm run test:platform # Platform-specific testsPlatform-specific testing
npm run test:linux # Linux-only tests
npm run test:macos # macOS-only tests
npm run test:windows # Windows-only tests
npm run test:current-platform # Current platform onlyCoverage and reporting
npm run test:coverage # With coverage report
npm run test:watch # Watch mode
`Test Structure:
-
test/unit/ - Unit tests for individual components
- test/integration/ - Integration tests
- test/platform/ - Platform-specific functionality tests
- test/utils/ - Test utilities and helpers$3
1. Fork & Clone
`bash
git fork https://github.com/SunilWang/node-os-utils.git
git clone https://github.com/yourusername/node-os-utils.git
`2. Create Feature Branch
`bash
git checkout -b feature/your-feature-name
`3. Development Setup
`bash
npm install
npm run build:watch # Start development build
`4. Make Changes
- Follow TypeScript best practices
- Add comprehensive tests
- Update documentation if needed
- Follow existing code patterns
5. Quality Checks
`bash
npm run lint # Code linting
npm test # All tests
npm run test:coverage # Coverage check
npm run build # Build check
`6. Commit & Push
`bash
git add .
git commit -m "feat: add new feature description"
git push origin feature/your-feature-name
`7. Submit Pull Request
- Provide clear description
- Include test results
- Reference related issues
$3
- Use TypeScript strict mode
- Follow existing naming conventions
- Add JSDoc comments for public APIs
- Maintain cross-platform compatibility
- Include comprehensive error handling
- Write tests for new functionality
$3
When reporting issues, please include:
- Node.js version
- Operating system and version
- Complete error messages
- Minimal reproduction example
- Expected vs actual behavior
๐ Performance & Benchmarks
$3
| Operation | Typical Time | Cache Hit Time | Memory Usage |
|-----------|-------------|----------------|---------------|
| CPU Info | 50-100ms | <1ms | ~2KB |
| CPU Usage | 100-500ms | <1ms | ~1KB |
| Memory Info | 10-50ms | <1ms | ~3KB |
| Disk Info | 100-300ms | <1ms | ~5KB |
| Network Stats | 50-150ms | <1ms | ~4KB |
| Process List | 200-1000ms | <1ms | ~50KB |
$3
`typescript
// Enable caching for better performance
const osutils = new OSUtils({
cacheEnabled: true,
cacheTTL: 5000 // 5 second cache
});// Use appropriate cache TTL for different metrics
const config = {
cpu: { cacheTTL: 1000 }, // Fast changing
memory: { cacheTTL: 3000 }, // Medium changing
disk: { cacheTTL: 30000 }, // Slow changing
};
`๐ Monitoring Best Practices
1. Cache Strategy: Use appropriate TTL values based on data change frequency
2. Error Handling: Always check
result.success` before accessing data- systeminformation - Alternative system information library
- node-machine-id - Unique machine identification
- cpu-features - CPU feature detection
Q: Why does some functionality not work on Windows?
A: Windows has different system APIs and command structures. Some features like detailed I/O stats are limited by Windows capabilities.
Q: How accurate are the measurements?
A: Accuracy depends on platform and measurement type. CPU usage is sampled over time, memory info is instantaneous, disk info reflects current filesystem state.
Q: Can I use this in production?
A: Yes, but implement proper error handling and consider the performance impact of frequent system calls.
Q: How do I reduce memory usage?
A: Configure appropriate cache settings and avoid keeping long-running monitoring subscriptions if not needed.
MIT License. See LICENSE file for details.
Copyright (c) 2024 node-os-utils contributors
---
Built with โค๏ธ and TypeScript
Star โญ this repo if you find it useful!
[npm-image]: https://img.shields.io/npm/v/node-os-utils.svg
[npm-url]: https://www.npmjs.com/package/node-os-utils
[downloads-image]: https://img.shields.io/npm/dt/node-os-utils.svg
[downloads-url]: https://npmjs.org/package/node-os-utils