node-os-utils v3.1.0
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]

🚀 Version 3.1.0 - Builds on v3.0's security, data-accuracy, and focused legacy-behavior improvements while preserving the zero-dependency package and the v3 API, broadening Node.js runtime compatibility, and modernizing the development security toolchain.
Modern, TypeScript-native, cross-platform system monitoring library providing comprehensive system information with intelligent caching, event-driven monitoring, and robust error handling.
Upgrade notice: Version 3.0 contains targeted breaking changes from 2.x. See Migration from v2.x to v3.0 before upgrading.
✨ What's New in v3.1.0
- Broader Runtime Support: The published package now supports Node.js 12.22.0 and later
- CommonJS and Native ESM: Package-root imports are verified in both module systems on the minimum supported runtime
- Zero Runtime Dependencies: Development-tool upgrades do not add dependencies to the published package
- Release Validation: CI builds with Node.js 20.20.2 and tests the real npm tarball on exact Node.js 12.22.0
✨ What's New in v3.0
🎯 Reliability Improvements
- ⏱️ Truthful Process Timing: Unavailable
startTime, runtime, and user loginTime values are reported as undefined instead of fabricated timestamps
- 🛡️ Safer Process Signalling: Process termination only accepts positive safe-integer PIDs, preventing accidental process-group signals
- ⚙️ Predictable Configuration: Disabling system information now consistently affects
info() and overview()
- 📊 Valid Data Sizes:
DataSize rejects non-finite values before they can propagate through calculations
- 🌍 Cross-Platform Accuracy: More robust parsing, error reporting, and health checks across Linux, macOS, and Windows
- ⚡ Resilient Execution: Improved command timeouts and failure handling prevent monitoring operations from becoming a source of instability
🌟 Key Features
- 🌍 Cross-Platform: Linux, macOS, Windows support with intelligent platform adaptation
- 📝 Zero Dependencies: Pure Node.js implementation using only built-in modules
- ⚙️ Configurable: Flexible configuration system for caching, timeouts, and monitoring
- 🎯 Type Safe: Full TypeScript definitions with IntelliSense support
- 🔍 Comprehensive: CPU, Memory, Disk, Network, Process, and System monitoring
- 📈 Real-time: Event-driven monitoring with customizable intervals
- ✅ Accurate State Reporting: Network adapters preserve native interface status while falling back to inferred states when unavailable
🧱 Architecture at a Glance
-
AdapterFactory centralises platform detection, caching instantiated adapters and exposing helper utilities such as getSupportedPlatforms() and checkPlatformCapabilities().
-
CommandExecutor normalises shell execution across operating systems with configurable timeouts and uniform error objects.
Command availability checks and version queries use the executor's configured timeout. Both propagate TIMEOUT errors; a timed-out availability check does not return false. Buffered execution attempts to terminate the process tree on timeout or output overflow, preserving encoding and separate stdout/stderr byte limits.
-
Platform Adapters encapsulate OS-specific logic (Linux via /proc, macOS via sysctl/powermetrics, Windows via PowerShell + WMI) while reporting declared feature support.
-
CacheManager provides adaptive TTL-based caching with LRU eviction to minimise expensive system calls during polling-heavy workloads.
🖥️ Platform Support Matrix
| 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
🔍 Capability Diagnostics
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.issues.length > 0) {
console.warn('❗ Capability diagnostics:', report.issues);
}
OSUtils.checkPlatformCapabilities() reuses the instance's adapter and command timeout. supported remains false for unsupported platforms, adapter initialization failures, or feature enumeration failures. Individual command/file probe failures, including TIMEOUT, appear in issues alongside any successfully detected capabilities. The static AdapterFactory.checkPlatformCapabilities(platformOrAdapter?) accepts either a platform name or an existing adapter to reuse its configuration; existing calls with a platform name remain valid.
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;
- disables service inspection (
systemctl) for non-systemd environments;
- falls back from
ss to netstat and from ip to ifconfig when tooling is missing;
- returns rich error details so that callers can differentiate permission issues from unsupported features;
- keeps feature flags in sync via
adapter.getSupportedFeatures() so monitors can short-circuit unsupported actions.
🚀 Installation
npm install node-os-utils
Requirements:
- Runtime: Node.js 12.22.0 or higher
- Repository development and testing: use the Node.js 20.20.2 version pinned by
.node-version (the toolchain requires ^20.19.0 || >=22.12.0)
- Supported OS: Linux, macOS, Windows
🏁 Quick Start
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 (CommonJS)
const { OSUtils } = require('node-os-utils');
const osutils = new OSUtils();
osutils.cpu.usage().then(result => {
if (result.success) {
console.log('CPU Usage:', result.data + '%');
}
});
Alternative Factory Function
// 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();
⚙️ Configuration
Global Configuration
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils({
// Cache settings
cacheEnabled: true,
cacheTTL: 5000,
maxCacheSize: 1000,
// Execution settings
// Timeout (ms), applies to both monitor operations and underlying system commands
timeout: 10000,
// Debug mode
debug: false,
// Monitor-specific configurations
cpu: {
cacheTTL: 30000,
// Exclude iowait from the overall CPU usage percentage (Linux only).
// Default: false (iowait is included, matching traditional tool behavior)
excludeIowait: false
},
memory: { cacheTTL: 5000 },
disk: { cacheTTL: 60000 }
});
Monitor-Level Configuration
// 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
});
🛡️ Error Handling
All operations return a MonitorResult<T> object for consistent error handling:
type MonitorResult<T> =
| {
success: true;
data: T;
timestamp: number;
cached: boolean;
platform: string;
}
| {
success: false;
error: MonitorError;
platform: string;
timestamp: number;
};
Error Handling Examples
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);
}
}
Error Codes
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
}
🛠️ Troubleshooting & Permissions
- 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.
- Windows network & process metrics call PowerShell CIM cmdlets (
Get-NetAdapterStatistics, Get-CimInstance). Run the host app in an elevated PowerShell session if you encounter PERMISSION_DENIED or COMMAND_FAILED errors.
- Linux command fallbacks: metrics primarily read
/proc. If utilities such as ip/ss are missing, the adapter retries with ifconfig/netstat, but you can confirm availability up front via osutils.checkPlatformCapabilities().
- Always inspect
MonitorResult.error.code for structured error feedback (timeout, permission, unsupported) and provide user guidance accordingly.
- Command timeouts retain
TIMEOUT through adapter error handling. macOS CPU and Linux network queries stop on timeout instead of starting a fallback command; Windows gateway and service queries report timeout instead of returning an empty or unsupported result. Existing Node.js os data fallbacks remain available.
📚 Complete API Reference
🔥 CPU Monitor
Comprehensive CPU monitoring with real-time capabilities.
// 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<MonitorResult<CPUInfo>> |
CPU model, cores, threads, architecture |
✅ All |
usage() |
Promise<MonitorResult<number>> |
CPU usage percentage (0-100) |
✅ All |
usageDetailed() |
Promise<MonitorResult<CPUUsage>> |
Usage breakdown including per-core data |
✅ All |
usageByCore() |
Promise<MonitorResult<number[]>> |
Per-core usage percentages |
✅ All |
loadAverage() |
Promise<MonitorResult<LoadAverage>> |
Load averages (1, 5, 15 min) |
✅ Linux/macOS |
temperature() |
Promise<MonitorResult<Temperature[]>> |
CPU temperature sensors |
⚠️ Limited |
frequency() |
Promise<MonitorResult<FrequencyInfo[]>> |
Current CPU frequencies |
⚠️ Limited |
getCacheInfo() |
Promise<MonitorResult<any>> |
CPU cache hierarchy information |
⚠️ Limited |
coreCount() |
Promise<MonitorResult<{ physical: number; logical: number }>> |
Physical/logical core counts |
✅ All |
CPU Configuration
| Option |
Type |
Default |
Description |
excludeIowait |
boolean |
false |
When true, I/O wait time is excluded from the overall CPU usage percentage. Useful in I/O-heavy environments where iowait would otherwise inflate reported CPU usage. iowait is still available as a separate field in usageDetailed(). Linux only. |