node-os-utils 1.3.7 → 2.0.1-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1113 -237
- package/dist/.tsbuildinfo +1 -0
- package/dist/package.json +99 -0
- package/dist/src/adapters/adapter-factory.d.ts +87 -0
- package/dist/src/adapters/adapter-factory.d.ts.map +1 -0
- package/dist/src/adapters/adapter-factory.js +272 -0
- package/dist/src/adapters/adapter-factory.js.map +1 -0
- package/dist/src/adapters/linux-adapter.d.ts +199 -0
- package/dist/src/adapters/linux-adapter.d.ts.map +1 -0
- package/dist/src/adapters/linux-adapter.js +1308 -0
- package/dist/src/adapters/linux-adapter.js.map +1 -0
- package/dist/src/adapters/macos-adapter.d.ts +232 -0
- package/dist/src/adapters/macos-adapter.d.ts.map +1 -0
- package/dist/src/adapters/macos-adapter.js +1144 -0
- package/dist/src/adapters/macos-adapter.js.map +1 -0
- package/dist/src/adapters/windows-adapter.d.ts +124 -0
- package/dist/src/adapters/windows-adapter.d.ts.map +1 -0
- package/dist/src/adapters/windows-adapter.js +601 -0
- package/dist/src/adapters/windows-adapter.js.map +1 -0
- package/dist/src/core/base-monitor.d.ts +107 -0
- package/dist/src/core/base-monitor.d.ts.map +1 -0
- package/dist/src/core/base-monitor.js +312 -0
- package/dist/src/core/base-monitor.js.map +1 -0
- package/dist/src/core/cache-manager.d.ts +157 -0
- package/dist/src/core/cache-manager.d.ts.map +1 -0
- package/dist/src/core/cache-manager.js +315 -0
- package/dist/src/core/cache-manager.js.map +1 -0
- package/dist/src/core/platform-adapter.d.ts +197 -0
- package/dist/src/core/platform-adapter.d.ts.map +1 -0
- package/dist/src/core/platform-adapter.js +244 -0
- package/dist/src/core/platform-adapter.js.map +1 -0
- package/dist/src/index.d.ts +205 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +315 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/monitors/cpu-monitor.d.ts +139 -0
- package/dist/src/monitors/cpu-monitor.d.ts.map +1 -0
- package/dist/src/monitors/cpu-monitor.js +433 -0
- package/dist/src/monitors/cpu-monitor.js.map +1 -0
- package/dist/src/monitors/disk-monitor.d.ts +136 -0
- package/dist/src/monitors/disk-monitor.d.ts.map +1 -0
- package/dist/src/monitors/disk-monitor.js +465 -0
- package/dist/src/monitors/disk-monitor.js.map +1 -0
- package/dist/src/monitors/memory-monitor.d.ts +136 -0
- package/dist/src/monitors/memory-monitor.d.ts.map +1 -0
- package/dist/src/monitors/memory-monitor.js +443 -0
- package/dist/src/monitors/memory-monitor.js.map +1 -0
- package/dist/src/monitors/network-monitor.d.ts +166 -0
- package/dist/src/monitors/network-monitor.d.ts.map +1 -0
- package/dist/src/monitors/network-monitor.js +586 -0
- package/dist/src/monitors/network-monitor.js.map +1 -0
- package/dist/src/monitors/process-monitor.d.ts +142 -0
- package/dist/src/monitors/process-monitor.d.ts.map +1 -0
- package/dist/src/monitors/process-monitor.js +460 -0
- package/dist/src/monitors/process-monitor.js.map +1 -0
- package/dist/src/monitors/system-monitor.d.ts +173 -0
- package/dist/src/monitors/system-monitor.d.ts.map +1 -0
- package/dist/src/monitors/system-monitor.js +592 -0
- package/dist/src/monitors/system-monitor.js.map +1 -0
- package/dist/src/types/common.d.ts +135 -0
- package/dist/src/types/common.d.ts.map +1 -0
- package/dist/src/types/common.js +141 -0
- package/dist/src/types/common.js.map +1 -0
- package/dist/src/types/config.d.ts +288 -0
- package/dist/src/types/config.d.ts.map +1 -0
- package/dist/src/types/config.js +3 -0
- package/dist/src/types/config.js.map +1 -0
- package/dist/src/types/errors.d.ts +40 -0
- package/dist/src/types/errors.d.ts.map +1 -0
- package/dist/src/types/errors.js +67 -0
- package/dist/src/types/errors.js.map +1 -0
- package/dist/src/types/index.d.ts +16 -0
- package/dist/src/types/index.d.ts.map +1 -0
- package/dist/src/types/index.js +36 -0
- package/dist/src/types/index.js.map +1 -0
- package/dist/src/types/monitors.d.ts +623 -0
- package/dist/src/types/monitors.d.ts.map +1 -0
- package/dist/src/types/monitors.js +3 -0
- package/dist/src/types/monitors.js.map +1 -0
- package/dist/src/types/platform.d.ts +435 -0
- package/dist/src/types/platform.d.ts.map +1 -0
- package/dist/src/types/platform.js +3 -0
- package/dist/src/types/platform.js.map +1 -0
- package/dist/src/utils/command-executor.d.ts +58 -0
- package/dist/src/utils/command-executor.d.ts.map +1 -0
- package/dist/src/utils/command-executor.js +321 -0
- package/dist/src/utils/command-executor.js.map +1 -0
- package/dist/test/config/test-config.d.ts +301 -0
- package/dist/test/config/test-config.d.ts.map +1 -0
- package/dist/test/config/test-config.js +235 -0
- package/dist/test/config/test-config.js.map +1 -0
- package/dist/test/platform/linux.test.d.ts +6 -0
- package/dist/test/platform/linux.test.d.ts.map +1 -0
- package/dist/test/platform/linux.test.js +307 -0
- package/dist/test/platform/linux.test.js.map +1 -0
- package/dist/test/platform/macos.test.d.ts +6 -0
- package/dist/test/platform/macos.test.d.ts.map +1 -0
- package/dist/test/platform/macos.test.js +276 -0
- package/dist/test/platform/macos.test.js.map +1 -0
- package/dist/test/platform/windows.test.d.ts +6 -0
- package/dist/test/platform/windows.test.d.ts.map +1 -0
- package/dist/test/platform/windows.test.js +320 -0
- package/dist/test/platform/windows.test.js.map +1 -0
- package/dist/test/unit/adapters/adapter-factory.test.d.ts +2 -0
- package/dist/test/unit/adapters/adapter-factory.test.d.ts.map +1 -0
- package/dist/test/unit/adapters/adapter-factory.test.js +147 -0
- package/dist/test/unit/adapters/adapter-factory.test.js.map +1 -0
- package/dist/test/unit/adapters/linux-adapter.test.d.ts +2 -0
- package/dist/test/unit/adapters/linux-adapter.test.d.ts.map +1 -0
- package/dist/test/unit/adapters/linux-adapter.test.js +191 -0
- package/dist/test/unit/adapters/linux-adapter.test.js.map +1 -0
- package/dist/test/unit/adapters/macos-adapter.test.d.ts +2 -0
- package/dist/test/unit/adapters/macos-adapter.test.d.ts.map +1 -0
- package/dist/test/unit/adapters/macos-adapter.test.js +224 -0
- package/dist/test/unit/adapters/macos-adapter.test.js.map +1 -0
- package/dist/test/unit/adapters/windows-adapter.test.d.ts +2 -0
- package/dist/test/unit/adapters/windows-adapter.test.d.ts.map +1 -0
- package/dist/test/unit/adapters/windows-adapter.test.js +41 -0
- package/dist/test/unit/adapters/windows-adapter.test.js.map +1 -0
- package/dist/test/unit/core/base-monitor.test.d.ts +2 -0
- package/dist/test/unit/core/base-monitor.test.d.ts.map +1 -0
- package/dist/test/unit/core/base-monitor.test.js +157 -0
- package/dist/test/unit/core/base-monitor.test.js.map +1 -0
- package/dist/test/unit/core/cache-manager.test.d.ts +6 -0
- package/dist/test/unit/core/cache-manager.test.d.ts.map +1 -0
- package/dist/test/unit/core/cache-manager.test.js +127 -0
- package/dist/test/unit/core/cache-manager.test.js.map +1 -0
- package/dist/test/unit/core/platform-adapter.test.d.ts +2 -0
- package/dist/test/unit/core/platform-adapter.test.d.ts.map +1 -0
- package/dist/test/unit/core/platform-adapter.test.js +186 -0
- package/dist/test/unit/core/platform-adapter.test.js.map +1 -0
- package/dist/test/unit/index.test.d.ts +2 -0
- package/dist/test/unit/index.test.d.ts.map +1 -0
- package/dist/test/unit/index.test.js +183 -0
- package/dist/test/unit/index.test.js.map +1 -0
- package/dist/test/unit/monitors/cpu-monitor.test.d.ts +2 -0
- package/dist/test/unit/monitors/cpu-monitor.test.d.ts.map +1 -0
- package/dist/test/unit/monitors/cpu-monitor.test.js +166 -0
- package/dist/test/unit/monitors/cpu-monitor.test.js.map +1 -0
- package/dist/test/unit/monitors/disk-monitor.test.d.ts +2 -0
- package/dist/test/unit/monitors/disk-monitor.test.d.ts.map +1 -0
- package/dist/test/unit/monitors/disk-monitor.test.js +46 -0
- package/dist/test/unit/monitors/disk-monitor.test.js.map +1 -0
- package/dist/test/unit/monitors/memory-monitor.test.d.ts +2 -0
- package/dist/test/unit/monitors/memory-monitor.test.d.ts.map +1 -0
- package/dist/test/unit/monitors/memory-monitor.test.js +142 -0
- package/dist/test/unit/monitors/memory-monitor.test.js.map +1 -0
- package/dist/test/unit/monitors/network-monitor.test.d.ts +2 -0
- package/dist/test/unit/monitors/network-monitor.test.d.ts.map +1 -0
- package/dist/test/unit/monitors/network-monitor.test.js +22 -0
- package/dist/test/unit/monitors/network-monitor.test.js.map +1 -0
- package/dist/test/unit/monitors/process-monitor.test.d.ts +2 -0
- package/dist/test/unit/monitors/process-monitor.test.d.ts.map +1 -0
- package/dist/test/unit/monitors/process-monitor.test.js +165 -0
- package/dist/test/unit/monitors/process-monitor.test.js.map +1 -0
- package/dist/test/unit/monitors/system-monitor-macos.test.d.ts +2 -0
- package/dist/test/unit/monitors/system-monitor-macos.test.d.ts.map +1 -0
- package/dist/test/unit/monitors/system-monitor-macos.test.js +115 -0
- package/dist/test/unit/monitors/system-monitor-macos.test.js.map +1 -0
- package/dist/test/unit/monitors/system-monitor.test.d.ts +2 -0
- package/dist/test/unit/monitors/system-monitor.test.d.ts.map +1 -0
- package/dist/test/unit/monitors/system-monitor.test.js +70 -0
- package/dist/test/unit/monitors/system-monitor.test.js.map +1 -0
- package/dist/test/unit/types/common.test.d.ts +6 -0
- package/dist/test/unit/types/common.test.d.ts.map +1 -0
- package/dist/test/unit/types/common.test.js +139 -0
- package/dist/test/unit/types/common.test.js.map +1 -0
- package/dist/test/unit/types/config.test.d.ts +2 -0
- package/dist/test/unit/types/config.test.d.ts.map +1 -0
- package/dist/test/unit/types/config.test.js +9 -0
- package/dist/test/unit/types/config.test.js.map +1 -0
- package/dist/test/unit/types/errors.test.d.ts +6 -0
- package/dist/test/unit/types/errors.test.d.ts.map +1 -0
- package/dist/test/unit/types/errors.test.js +184 -0
- package/dist/test/unit/types/errors.test.js.map +1 -0
- package/dist/test/unit/types/index.test.d.ts +2 -0
- package/dist/test/unit/types/index.test.d.ts.map +1 -0
- package/dist/test/unit/types/index.test.js +39 -0
- package/dist/test/unit/types/index.test.js.map +1 -0
- package/dist/test/unit/types/monitors.test.d.ts +2 -0
- package/dist/test/unit/types/monitors.test.d.ts.map +1 -0
- package/dist/test/unit/types/monitors.test.js +9 -0
- package/dist/test/unit/types/monitors.test.js.map +1 -0
- package/dist/test/unit/types/platform.test.d.ts +2 -0
- package/dist/test/unit/types/platform.test.d.ts.map +1 -0
- package/dist/test/unit/types/platform.test.js +9 -0
- package/dist/test/unit/types/platform.test.js.map +1 -0
- package/dist/test/unit/utils/command-executor.test.d.ts +6 -0
- package/dist/test/unit/utils/command-executor.test.d.ts.map +1 -0
- package/dist/test/unit/utils/command-executor.test.js +153 -0
- package/dist/test/unit/utils/command-executor.test.js.map +1 -0
- package/dist/test/unit/utils/platform-specific.test.d.ts +2 -0
- package/dist/test/unit/utils/platform-specific.test.d.ts.map +1 -0
- package/dist/test/unit/utils/platform-specific.test.js +32 -0
- package/dist/test/unit/utils/platform-specific.test.js.map +1 -0
- package/dist/test/utils/platform-specific.d.ts +139 -0
- package/dist/test/utils/platform-specific.d.ts.map +1 -0
- package/dist/test/utils/platform-specific.js +306 -0
- package/dist/test/utils/platform-specific.js.map +1 -0
- package/dist/test/utils/test-base.d.ts +157 -0
- package/dist/test/utils/test-base.d.ts.map +1 -0
- package/dist/test/utils/test-base.js +316 -0
- package/dist/test/utils/test-base.js.map +1 -0
- package/package.json +78 -18
- package/.travis.yml +0 -7
- package/index.js +0 -17
- package/lib/bucket.js +0 -14
- package/lib/cpu.js +0 -94
- package/lib/drive.js +0 -113
- package/lib/exec.js +0 -28
- package/lib/mem.js +0 -176
- package/lib/netstat.js +0 -182
- package/lib/openfiles.js +0 -25
- package/lib/os.js +0 -148
- package/lib/osCmd.js +0 -20
- package/lib/proc.js +0 -38
- package/lib/users.js +0 -18
- package/test/test.js +0 -55
- package/util/co.js +0 -237
- package/util/index.js +0 -12
package/README.md
CHANGED
|
@@ -1,349 +1,1225 @@
|
|
|
1
|
-
|
|
1
|
+
# node-os-utils v2.0
|
|
2
2
|
|
|
3
|
-
monitor vital signs of your server :
|
|
4
|
-
|
|
5
|
-
- CPU average usage
|
|
6
|
-
- Free and used drive space
|
|
7
|
-
- Free and used memory space
|
|
8
|
-
- Operating System
|
|
9
|
-
- All processes running
|
|
10
|
-
- TTY/SSH opened
|
|
11
|
-
- Total opened files
|
|
12
|
-
- Network speed (input and output)
|
|
13
|
-
|
|
14
|
-
# node-os-utils
|
|
15
|
-
|
|
16
|
-
[](https://standardjs.com)
|
|
17
|
-
[](https://travis-ci.org/SunilWang/node-os-utils)
|
|
18
3
|
[![NPM Version][npm-image]][npm-url]
|
|
19
4
|
[![NPM Downloads][downloads-image]][downloads-url]
|
|
5
|
+
[](https://www.typescriptlang.org/)
|
|
6
|
+
[](https://nodejs.org/)
|
|
7
|
+
[](https://opensource.org/licenses/MIT)
|
|
8
|
+
|
|
9
|
+
🚀 **Version 2.0** - A complete rewrite of the popular Node.js operating system monitoring library.
|
|
10
|
+
|
|
11
|
+
**Modern, TypeScript-native, cross-platform system monitoring library** providing comprehensive system information with intelligent caching, event-driven monitoring, and robust error handling.
|
|
12
|
+
|
|
13
|
+
> **Breaking Changes**: This is a major version release with breaking changes from v1.x.
|
|
14
|
+
|
|
15
|
+
## ✨ What's New in v2.0
|
|
16
|
+
|
|
17
|
+
### 🎯 Core Improvements
|
|
18
|
+
- **🔧 TypeScript First**: Complete rewrite in TypeScript with strict typing
|
|
19
|
+
- **🏗️ Modern Architecture**: Clean, modular design with adapter pattern
|
|
20
|
+
- **⚡ Performance Optimized**: Intelligent caching system with TTL management
|
|
21
|
+
- **🛡️ Robust Error Handling**: Consistent error handling with detailed error codes
|
|
22
|
+
- **🔄 Event-Driven**: Real-time monitoring with subscription management
|
|
23
|
+
- **📊 Rich Data Types**: Comprehensive data structures with unit conversions
|
|
24
|
+
- **📆 Timeline Aware**: System info now exposes `bootTime` & `uptimeSeconds`, and Linux process metrics include precise `startTime`
|
|
25
|
+
|
|
26
|
+
### 🌟 Key Features
|
|
27
|
+
- **🌍 Cross-Platform**: Linux, macOS, Windows support with intelligent platform adaptation
|
|
28
|
+
- **📝 Zero Dependencies**: Pure Node.js implementation using only built-in modules
|
|
29
|
+
- **⚙️ Configurable**: Flexible configuration system for caching, timeouts, and monitoring
|
|
30
|
+
- **🎯 Type Safe**: Full TypeScript definitions with IntelliSense support
|
|
31
|
+
- **🔍 Comprehensive**: CPU, Memory, Disk, Network, Process, and System monitoring
|
|
32
|
+
- **📈 Real-time**: Event-driven monitoring with customizable intervals
|
|
33
|
+
- **✅ Accurate State Reporting**: Network adapters preserve native interface status while falling back to inferred states when unavailable
|
|
34
|
+
|
|
35
|
+
### 🧱 Architecture at a Glance
|
|
36
|
+
- **AdapterFactory** centralises platform detection, caching instantiated adapters and exposing helper utilities such as `getSupportedPlatforms()` and `checkPlatformCapabilities()`.
|
|
37
|
+
- **CommandExecutor** normalises shell execution across operating systems with smart fallbacks (`/bin/bash` → `/bin/sh`, PowerShell auto discovery) and uniform error objects.
|
|
38
|
+
- **Platform Adapters** encapsulate OS-specific logic (Linux via `/proc`, macOS via `sysctl`/`powermetrics`, Windows via PowerShell + WMI) while reporting declared feature support.
|
|
39
|
+
- **CacheManager** provides adaptive TTL-based caching with LRU eviction to minimise expensive system calls during polling-heavy workloads.
|
|
40
|
+
|
|
41
|
+
### 🖥️ Platform Support Matrix
|
|
42
|
+
|
|
43
|
+
| Capability | Linux | macOS | Windows |
|
|
44
|
+
|------------|:-----:|:-----:|:-------:|
|
|
45
|
+
| CPU usage / info | ✅ | ✅ | ✅ |
|
|
46
|
+
| CPU temperature | ⚠️ Needs `/sys/class/thermal` | ⚠️ Requires `powermetrics` (sudo) | ❌ (no public API) |
|
|
47
|
+
| Memory pressure | ⚠️ Partially available | ✅ | ⚠️ Estimated via WMI |
|
|
48
|
+
| Disk IO stats | ✅ | ✅ | ❌ |
|
|
49
|
+
| Network stats | ✅ (`/proc/net/dev`) | ✅ (`netstat -ib`) | ⚠️ Admin rights for PowerShell |
|
|
50
|
+
| Process details | ✅ | ✅ | ✅ (WMI) |
|
|
51
|
+
| System services | ⚠️ `systemctl` when available | ❌ | ✅ |
|
|
52
|
+
| Container awareness | ⚠️ Detects containers, gracefully degrades | ⚠️ Detects containers, limited | ⚠️ Detects containers, limited |
|
|
53
|
+
|
|
54
|
+
> **Legend**: ✅ Fully supported · ⚠️ Partially limited · ❌ Not supported
|
|
55
|
+
|
|
56
|
+
### 🔍 Capability Diagnostics
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { OSUtils } from 'node-os-utils';
|
|
60
|
+
|
|
61
|
+
const osutils = new OSUtils();
|
|
62
|
+
const report = await osutils.checkPlatformCapabilities();
|
|
63
|
+
|
|
64
|
+
console.table({
|
|
65
|
+
platform: report.platform,
|
|
66
|
+
supported: report.supported,
|
|
67
|
+
commands: report.capabilities.commands.join(','),
|
|
68
|
+
features: report.capabilities.features.join(',')
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
if (!report.supported) {
|
|
72
|
+
console.warn('❗ Some metrics are unavailable:', report.issues);
|
|
73
|
+
}
|
|
74
|
+
```
|
|
20
75
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
[os-utils](https://github.com/oscmejia/os-utils) extended
|
|
76
|
+
`AdapterFactory.getDebugInfo()` is also available when you need to inspect feature flags or confirm that platform-specific commands can be executed.
|
|
24
77
|
|
|
25
|
-
|
|
78
|
+
When running inside **containers**, the library automatically:
|
|
79
|
+
- detects Docker/Podman/Kubernetes via `.dockerenv`, `/proc/1/cgroup`, or env vars;
|
|
80
|
+
- disables service inspection (`systemctl`) for non-systemd environments;
|
|
81
|
+
- falls back from `ss` to `netstat` and from `ip` to `ifconfig` when tooling is missing;
|
|
82
|
+
- returns rich error details so that callers can differentiate permission issues from unsupported features;
|
|
83
|
+
- keeps feature flags in sync via `adapter.getSupportedFeatures()` so monitors can short-circuit unsupported actions.
|
|
26
84
|
|
|
27
|
-
|
|
85
|
+
## 🚀 Installation
|
|
28
86
|
|
|
29
87
|
```bash
|
|
30
|
-
|
|
88
|
+
npm install node-os-utils
|
|
31
89
|
```
|
|
32
|
-
Then in your code
|
|
33
90
|
|
|
34
|
-
|
|
91
|
+
**Requirements:**
|
|
92
|
+
- Node.js 18.0.0 or higher
|
|
93
|
+
- Supported OS: Linux, macOS, Windows
|
|
35
94
|
|
|
36
|
-
|
|
37
|
-
var osu = require('node-os-utils')
|
|
38
|
-
var cpu = osu.cpu
|
|
95
|
+
## 🏁 Quick Start
|
|
39
96
|
|
|
40
|
-
|
|
97
|
+
### TypeScript
|
|
41
98
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
console.log(cpuPercentage) // 10.38
|
|
45
|
-
})
|
|
99
|
+
```typescript
|
|
100
|
+
import { OSUtils } from 'node-os-utils';
|
|
46
101
|
|
|
47
|
-
|
|
102
|
+
const osutils = new OSUtils();
|
|
48
103
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
104
|
+
// Get CPU usage
|
|
105
|
+
const cpuUsage = await osutils.cpu.usage();
|
|
106
|
+
if (cpuUsage.success) {
|
|
107
|
+
console.log('CPU Usage:', cpuUsage.data + '%');
|
|
108
|
+
}
|
|
54
109
|
|
|
55
|
-
|
|
110
|
+
// Get memory information
|
|
111
|
+
const memInfo = await osutils.memory.info();
|
|
112
|
+
if (memInfo.success) {
|
|
113
|
+
console.log('Memory:', memInfo.data);
|
|
114
|
+
}
|
|
56
115
|
|
|
57
|
-
|
|
116
|
+
// Get system overview
|
|
117
|
+
const overview = await osutils.overview();
|
|
118
|
+
console.log('System Overview:', overview);
|
|
119
|
+
```
|
|
58
120
|
|
|
59
|
-
|
|
121
|
+
### JavaScript (CommonJS)
|
|
60
122
|
|
|
61
|
-
|
|
62
|
-
|
|
123
|
+
```javascript
|
|
124
|
+
const { OSUtils } = require('node-os-utils');
|
|
63
125
|
|
|
64
|
-
|
|
126
|
+
const osutils = new OSUtils();
|
|
65
127
|
|
|
66
|
-
|
|
128
|
+
osutils.cpu.usage().then(result => {
|
|
129
|
+
if (result.success) {
|
|
130
|
+
console.log('CPU Usage:', result.data + '%');
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
```
|
|
67
134
|
|
|
68
|
-
|
|
135
|
+
### Alternative Factory Function
|
|
69
136
|
|
|
70
|
-
|
|
137
|
+
```javascript
|
|
138
|
+
// Alternative instantiation method
|
|
139
|
+
const { createOSUtils } = require('node-os-utils');
|
|
71
140
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
141
|
+
const osutils = createOSUtils({
|
|
142
|
+
cacheEnabled: true,
|
|
143
|
+
cacheTTL: 10000
|
|
144
|
+
});
|
|
75
145
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if(osu.isNotSupported(res)){
|
|
80
|
-
// Handle 'not supported'
|
|
81
|
-
}else{
|
|
82
|
-
// Things to do...
|
|
83
|
-
}
|
|
84
|
-
})
|
|
85
|
-
````
|
|
86
|
-
## Usage
|
|
87
|
-
The following methods are available:
|
|
146
|
+
// Same API as OSUtils class
|
|
147
|
+
const cpuUsage = await osutils.cpu.usage();
|
|
148
|
+
```
|
|
88
149
|
|
|
89
|
-
|
|
150
|
+
## ⚙️ Configuration
|
|
90
151
|
|
|
91
|
-
|
|
152
|
+
### Global Configuration
|
|
92
153
|
|
|
93
|
-
|
|
154
|
+
```typescript
|
|
155
|
+
import { OSUtils } from 'node-os-utils';
|
|
94
156
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
157
|
+
const osutils = new OSUtils({
|
|
158
|
+
// Cache settings
|
|
159
|
+
cacheEnabled: true,
|
|
160
|
+
cacheTTL: 5000,
|
|
161
|
+
maxCacheSize: 1000,
|
|
98
162
|
|
|
99
|
-
|
|
163
|
+
// Execution settings
|
|
164
|
+
timeout: 10000,
|
|
100
165
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
166
|
+
// Debug mode
|
|
167
|
+
debug: false,
|
|
168
|
+
|
|
169
|
+
// Monitor-specific configurations
|
|
170
|
+
cpu: { cacheTTL: 30000 },
|
|
171
|
+
memory: { cacheTTL: 5000 },
|
|
172
|
+
disk: { cacheTTL: 60000 }
|
|
173
|
+
});
|
|
108
174
|
```
|
|
109
175
|
|
|
110
|
-
|
|
176
|
+
### Monitor-Level Configuration
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
// Configure individual monitors
|
|
180
|
+
const cpuMonitor = osutils.cpu
|
|
181
|
+
.withCaching(true, 30000)
|
|
182
|
+
.withConfig({ timeout: 5000 });
|
|
111
183
|
|
|
112
|
-
|
|
184
|
+
// Configure cache at runtime
|
|
185
|
+
osutils.configureCache({
|
|
186
|
+
enabled: true,
|
|
187
|
+
maxSize: 2000,
|
|
188
|
+
defaultTTL: 10000
|
|
189
|
+
});
|
|
190
|
+
```
|
|
113
191
|
|
|
114
|
-
|
|
192
|
+
## 🛡️ Error Handling
|
|
115
193
|
|
|
116
|
-
|
|
117
|
-
var osu = require('node-os-utils')
|
|
118
|
-
var cpu = osu.cpu
|
|
194
|
+
All operations return a `MonitorResult<T>` object for consistent error handling:
|
|
119
195
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
196
|
+
```typescript
|
|
197
|
+
type MonitorResult<T> =
|
|
198
|
+
| {
|
|
199
|
+
success: true;
|
|
200
|
+
data: T;
|
|
201
|
+
timestamp: number;
|
|
202
|
+
cached: boolean;
|
|
203
|
+
platform: string;
|
|
204
|
+
}
|
|
205
|
+
| {
|
|
206
|
+
success: false;
|
|
207
|
+
error: MonitorError;
|
|
208
|
+
platform: string;
|
|
209
|
+
timestamp: number;
|
|
210
|
+
};
|
|
124
211
|
```
|
|
212
|
+
|
|
213
|
+
### Error Handling Examples
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
const result = await osutils.cpu.info();
|
|
217
|
+
|
|
218
|
+
if (result.success) {
|
|
219
|
+
// Success: use result.data
|
|
220
|
+
console.log('CPU Model:', result.data.model);
|
|
221
|
+
console.log('Cores:', result.data.cores);
|
|
222
|
+
} else {
|
|
223
|
+
// Error: handle gracefully
|
|
224
|
+
console.error('Error:', result.error?.message);
|
|
225
|
+
console.error('Code:', result.error?.code);
|
|
226
|
+
|
|
227
|
+
// Platform-specific handling
|
|
228
|
+
if (result.error?.code === ErrorCode.PLATFORM_NOT_SUPPORTED) {
|
|
229
|
+
console.log('This feature is not available on', result.platform);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
125
232
|
```
|
|
126
|
-
|
|
233
|
+
|
|
234
|
+
### Error Codes
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
enum ErrorCode {
|
|
238
|
+
PLATFORM_NOT_SUPPORTED = 'PLATFORM_NOT_SUPPORTED', // Feature unavailable on current platform
|
|
239
|
+
COMMAND_FAILED = 'COMMAND_FAILED', // Shell/command execution failed
|
|
240
|
+
PARSE_ERROR = 'PARSE_ERROR', // Failed to parse command output or data
|
|
241
|
+
PERMISSION_DENIED = 'PERMISSION_DENIED', // Lacking required privileges
|
|
242
|
+
TIMEOUT = 'TIMEOUT', // Operation exceeded the configured timeout
|
|
243
|
+
INVALID_CONFIG = 'INVALID_CONFIG', // Provided configuration is invalid
|
|
244
|
+
NOT_AVAILABLE = 'NOT_AVAILABLE', // Metric temporarily unavailable
|
|
245
|
+
FILE_NOT_FOUND = 'FILE_NOT_FOUND', // Required file or path missing
|
|
246
|
+
NETWORK_ERROR = 'NETWORK_ERROR' // Network operation failed
|
|
247
|
+
}
|
|
127
248
|
```
|
|
128
249
|
|
|
129
|
-
|
|
250
|
+
## 🛠️ Troubleshooting & Permissions
|
|
130
251
|
|
|
131
|
-
|
|
252
|
+
- **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.
|
|
253
|
+
- **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.
|
|
254
|
+
- **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()`.
|
|
255
|
+
- Always inspect `MonitorResult.error.code` for structured error feedback (timeout, permission, unsupported) and provide user guidance accordingly.
|
|
132
256
|
|
|
133
|
-
|
|
257
|
+
## 📚 Complete API Reference
|
|
134
258
|
|
|
135
|
-
|
|
136
|
-
var osu = require('node-os-utils')
|
|
137
|
-
var cpu = osu.cpu
|
|
259
|
+
### 🔥 CPU Monitor
|
|
138
260
|
|
|
139
|
-
|
|
140
|
-
.then(info => {
|
|
141
|
-
console.log(info)
|
|
142
|
-
})
|
|
143
|
-
```
|
|
144
|
-
```
|
|
145
|
-
89.26
|
|
146
|
-
```
|
|
147
|
-
#### cpu.count():number
|
|
148
|
-
#### cpu.model():string
|
|
149
|
-
#### cpu.loadavg():Array[number]
|
|
150
|
-
#### cpu.loadavgTime(time):number
|
|
261
|
+
Comprehensive CPU monitoring with real-time capabilities.
|
|
151
262
|
|
|
152
|
-
|
|
263
|
+
```typescript
|
|
264
|
+
// Basic CPU information
|
|
265
|
+
const cpuInfo = await osutils.cpu.info();
|
|
266
|
+
if (cpuInfo.success) {
|
|
267
|
+
console.log('Model:', cpuInfo.data.model);
|
|
268
|
+
console.log('Cores:', cpuInfo.data.cores);
|
|
269
|
+
console.log('Architecture:', cpuInfo.data.architecture);
|
|
270
|
+
}
|
|
153
271
|
|
|
154
|
-
|
|
272
|
+
// CPU usage monitoring
|
|
273
|
+
const cpuUsage = await osutils.cpu.usage();
|
|
274
|
+
if (cpuUsage.success) {
|
|
275
|
+
console.log('CPU Usage:', cpuUsage.data + '%');
|
|
276
|
+
}
|
|
155
277
|
|
|
156
|
-
|
|
278
|
+
// Detailed usage (overall + per core)
|
|
279
|
+
const usageDetails = await osutils.cpu.usageDetailed();
|
|
280
|
+
if (usageDetails.success) {
|
|
281
|
+
console.log('Overall:', usageDetails.data.overall);
|
|
282
|
+
console.log('Per core:', usageDetails.data.cores);
|
|
283
|
+
}
|
|
157
284
|
|
|
158
|
-
|
|
285
|
+
// Load average (Linux/macOS)
|
|
286
|
+
const loadAvg = await osutils.cpu.loadAverage();
|
|
287
|
+
if (loadAvg.success) {
|
|
288
|
+
console.log('Load Average:', loadAvg.data);
|
|
289
|
+
}
|
|
290
|
+
```
|
|
159
291
|
|
|
160
|
-
|
|
292
|
+
#### CPU Methods
|
|
293
|
+
|
|
294
|
+
| Method | Return Type | Description | Platform Support |
|
|
295
|
+
|--------|-------------|-------------|------------------|
|
|
296
|
+
| `info()` | `Promise<MonitorResult<CPUInfo>>` | CPU model, cores, threads, architecture | ✅ All |
|
|
297
|
+
| `usage()` | `Promise<MonitorResult<number>>` | CPU usage percentage (0-100) | ✅ All |
|
|
298
|
+
| `usageDetailed()` | `Promise<MonitorResult<CPUUsage>>` | Usage breakdown including per-core data | ✅ All |
|
|
299
|
+
| `usageByCore()` | `Promise<MonitorResult<number[]>>` | Per-core usage percentages | ✅ All |
|
|
300
|
+
| `loadAverage()` | `Promise<MonitorResult<LoadAverage>>` | Load averages (1, 5, 15 min) | ✅ Linux/macOS |
|
|
301
|
+
| `temperature()` | `Promise<MonitorResult<Temperature[]>>` | CPU temperature sensors | ⚠️ Limited |
|
|
302
|
+
| `frequency()` | `Promise<MonitorResult<FrequencyInfo[]>>` | Current CPU frequencies | ⚠️ Limited |
|
|
303
|
+
| `getCacheInfo()` | `Promise<MonitorResult<any>>` | CPU cache hierarchy information | ⚠️ Limited |
|
|
304
|
+
| `coreCount()` | `Promise<MonitorResult<{ physical: number; logical: number }>>` | Physical/logical core counts | ✅ All |
|
|
305
|
+
|
|
306
|
+
#### Real-time CPU Monitoring
|
|
307
|
+
|
|
308
|
+
```typescript
|
|
309
|
+
// Poll usage every second with manual interval control
|
|
310
|
+
const pollInterval = setInterval(async () => {
|
|
311
|
+
const result = await osutils.cpu.usage();
|
|
312
|
+
if (result.success) {
|
|
313
|
+
console.log(`CPU Usage: ${result.data.toFixed(2)}%`);
|
|
314
|
+
if (result.data > 80) {
|
|
315
|
+
console.warn('⚠️ High CPU usage detected!');
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}, 1000);
|
|
161
319
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
320
|
+
setTimeout(() => {
|
|
321
|
+
clearInterval(pollInterval);
|
|
322
|
+
console.log('CPU usage polling stopped');
|
|
323
|
+
}, 30000);
|
|
165
324
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
325
|
+
// Fetch CPU info periodically using the built-in monitor helper
|
|
326
|
+
const cpuInfoSubscription = osutils.cpu.withCaching(false).monitor(5000, (info) => {
|
|
327
|
+
console.log('CPU Model:', info.model);
|
|
328
|
+
});
|
|
170
329
|
|
|
330
|
+
setTimeout(() => cpuInfoSubscription.unsubscribe(), 20000);
|
|
171
331
|
```
|
|
332
|
+
|
|
333
|
+
### 💾 Memory Monitor
|
|
334
|
+
|
|
335
|
+
Detailed memory information with smart unit conversion.
|
|
336
|
+
|
|
337
|
+
```typescript
|
|
338
|
+
// Memory information with DataSize helpers
|
|
339
|
+
const memInfo = await osutils.memory.info();
|
|
340
|
+
if (memInfo.success) {
|
|
341
|
+
console.log('Total Memory:', memInfo.data.total.toGB().toFixed(2) + ' GB');
|
|
342
|
+
console.log('Available:', memInfo.data.available.toGB().toFixed(2) + ' GB');
|
|
343
|
+
console.log('Used:', memInfo.data.used.toGB().toFixed(2) + ' GB');
|
|
344
|
+
console.log('Usage:', memInfo.data.usagePercentage.toFixed(2) + '%');
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Quick memory usage percentage
|
|
348
|
+
const memUsage = await osutils.memory.usage();
|
|
349
|
+
if (memUsage.success) {
|
|
350
|
+
console.log('Memory Usage:', memUsage.data.toFixed(2) + '%');
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Summary view with formatted strings
|
|
354
|
+
const memSummary = await osutils.memory.summary();
|
|
355
|
+
if (memSummary.success) {
|
|
356
|
+
console.log('Summary:', memSummary.data);
|
|
357
|
+
}
|
|
172
358
|
```
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
359
|
+
|
|
360
|
+
#### Memory Methods
|
|
361
|
+
|
|
362
|
+
| Method | Return Type | Description | Platform Support |
|
|
363
|
+
|--------|-------------|-------------|------------------|
|
|
364
|
+
| `info()` | `Promise<MonitorResult<MemoryInfo>>` | Detailed memory breakdown with DataSize objects | ✅ All |
|
|
365
|
+
| `detailed()` | `Promise<MonitorResult<MemoryInfo & { breakdown: Record<string, unknown> }>>` | Adds platform-specific breakdown data | ⚠️ Platform |
|
|
366
|
+
| `usage()` | `Promise<MonitorResult<number>>` | Memory usage percentage (0-100) | ✅ All |
|
|
367
|
+
| `available()` | `Promise<MonitorResult<DataSize>>` | Available memory amount | ✅ All |
|
|
368
|
+
| `swap()` | `Promise<MonitorResult<SwapInfo>>` | Virtual memory/swap information | ✅ All |
|
|
369
|
+
| `pressure()` | `Promise<MonitorResult<MemoryPressure>>` | Memory pressure indicators | ⚠️ Limited |
|
|
370
|
+
| `summary()` | `Promise<MonitorResult<{ total: string; used: string; available: string; usagePercentage: number; swap: { total: string; used: string; usagePercentage: number } }>>` | Readable summary including swap usage | ✅ All |
|
|
371
|
+
|
|
372
|
+
#### DataSize Object
|
|
373
|
+
|
|
374
|
+
```typescript
|
|
375
|
+
class DataSize {
|
|
376
|
+
constructor(bytes: number);
|
|
377
|
+
toBytes(): number;
|
|
378
|
+
toKB(): number;
|
|
379
|
+
toMB(): number;
|
|
380
|
+
toGB(): number;
|
|
381
|
+
toTB(): number;
|
|
382
|
+
toString(unit?: 'auto' | 'B' | 'KB' | 'MB' | 'GB' | 'TB'): string;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// Usage example
|
|
386
|
+
const memory = await osutils.memory.info();
|
|
387
|
+
if (memory.success) {
|
|
388
|
+
console.log(memory.data.total.toString('GB')); // "16.00 GB"
|
|
389
|
+
console.log(memory.data.available.toString()); // automatic unit selection
|
|
390
|
+
}
|
|
178
391
|
```
|
|
179
392
|
|
|
180
|
-
|
|
393
|
+
### 💽 Disk Monitor
|
|
394
|
+
|
|
395
|
+
Comprehensive disk and storage monitoring.
|
|
396
|
+
|
|
397
|
+
```typescript
|
|
398
|
+
// All disk information
|
|
399
|
+
const diskInfo = await osutils.disk.info();
|
|
400
|
+
if (diskInfo.success) {
|
|
401
|
+
diskInfo.data.forEach(disk => {
|
|
402
|
+
console.log('Filesystem:', disk.filesystem);
|
|
403
|
+
console.log('Mount Point:', disk.mountpoint);
|
|
404
|
+
console.log('Total:', disk.total.toString('GB'));
|
|
405
|
+
console.log('Available:', disk.available.toString('GB'));
|
|
406
|
+
console.log('Usage:', disk.usagePercentage + '%');
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// Specific mount usage
|
|
411
|
+
const rootUsage = await osutils.disk.usageByMountPoint('/');
|
|
412
|
+
if (rootUsage.success && rootUsage.data) {
|
|
413
|
+
console.log('Root usage:', rootUsage.data.usagePercentage + '%');
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// I/O statistics
|
|
417
|
+
const ioStats = await osutils.disk.stats();
|
|
418
|
+
if (ioStats.success) {
|
|
419
|
+
ioStats.data.forEach(stat => {
|
|
420
|
+
console.log(`${stat.device}:`, {
|
|
421
|
+
readBytes: stat.readBytes.toString('MB'),
|
|
422
|
+
writeBytes: stat.writeBytes.toString('MB'),
|
|
423
|
+
readCount: stat.readCount,
|
|
424
|
+
writeCount: stat.writeCount
|
|
425
|
+
});
|
|
426
|
+
});
|
|
427
|
+
}
|
|
181
428
|
```
|
|
182
|
-
|
|
429
|
+
|
|
430
|
+
#### Disk Methods
|
|
431
|
+
|
|
432
|
+
| Method | Return Type | Description | Platform Support |
|
|
433
|
+
|--------|-------------|-------------|------------------|
|
|
434
|
+
| `info()` | `Promise<MonitorResult<DiskInfo[]>>` | Disk/partition information | ✅ All |
|
|
435
|
+
| `infoByDevice(device)` | `Promise<MonitorResult<DiskInfo | null>>` | Lookup device or mountpoint | ✅ All |
|
|
436
|
+
| `usage()` | `Promise<MonitorResult<DiskUsage[]>>` | Usage for mounted filesystems | ✅ All |
|
|
437
|
+
| `usageByMountPoint(mountPoint)` | `Promise<MonitorResult<DiskUsage | null>>` | Usage for a specific mount point | ✅ All |
|
|
438
|
+
| `overallUsage()` | `Promise<MonitorResult<number>>` | Weighted average usage across all disks | ✅ All |
|
|
439
|
+
| `stats()` | `Promise<MonitorResult<DiskStats[]>>` | I/O statistics summary (requires `includeStats`) | ⚠️ Limited |
|
|
440
|
+
| `mounts()` | `Promise<MonitorResult<MountPoint[]>>` | Mount configuration details | ✅ All |
|
|
441
|
+
| `filesystems()` | `Promise<MonitorResult<FileSystem[]>>` | Available filesystem types | ✅ All |
|
|
442
|
+
| `spaceOverview()` | `Promise<MonitorResult<{ total: DataSize; used: DataSize; available: DataSize; usagePercentage: number; disks: number }>>` | Aggregate space usage | ✅ All |
|
|
443
|
+
| `healthCheck()` | `Promise<MonitorResult<{ status: 'healthy' | 'warning' | 'critical'; issues: string[] }>>` | Basic disk health | ⚠️ Limited |
|
|
444
|
+
|
|
445
|
+
### 🌐 Network Monitor
|
|
446
|
+
|
|
447
|
+
Network interface and traffic monitoring.
|
|
448
|
+
|
|
449
|
+
```typescript
|
|
450
|
+
// Network interfaces
|
|
451
|
+
const interfaces = await osutils.network.interfaces();
|
|
452
|
+
if (interfaces.success) {
|
|
453
|
+
interfaces.data.forEach(iface => {
|
|
454
|
+
console.log('Interface:', iface.name);
|
|
455
|
+
console.log('Addresses:', iface.addresses);
|
|
456
|
+
console.log('State:', iface.state);
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// Network overview
|
|
461
|
+
const overview = await osutils.network.overview();
|
|
462
|
+
if (overview.success) {
|
|
463
|
+
console.log('Total RX:', overview.data.totalRxBytes.toString('MB'));
|
|
464
|
+
console.log('Total TX:', overview.data.totalTxBytes.toString('MB'));
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Per-interface statistics
|
|
468
|
+
const stats = await osutils.network.statsAsync();
|
|
469
|
+
if (stats.success) {
|
|
470
|
+
stats.data.forEach(stat => {
|
|
471
|
+
console.log(`${stat.interface}: RX ${stat.rxBytes.toString('MB')} | TX ${stat.txBytes.toString('MB')}`);
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// Real-time interface monitoring (returns NetworkInterface[] snapshots)
|
|
476
|
+
const netSub = osutils.network.monitor(5000, (interfacesSnapshot) => {
|
|
477
|
+
console.log('Active interfaces:', interfacesSnapshot.filter(iface => iface.state === 'up').map(iface => iface.name));
|
|
478
|
+
});
|
|
183
479
|
```
|
|
184
|
-
|
|
480
|
+
|
|
481
|
+
#### Network Methods
|
|
482
|
+
|
|
483
|
+
| Method | Return Type | Description | Platform Support |
|
|
484
|
+
|--------|-------------|-------------|------------------|
|
|
485
|
+
| `interfaces()` | `Promise<MonitorResult<NetworkInterface[]>>` | All network interfaces | ✅ All |
|
|
486
|
+
| `interfaceByName(name)` | `Promise<MonitorResult<NetworkInterface | null>>` | Single interface lookup | ✅ All |
|
|
487
|
+
| `overview()` | `Promise<MonitorResult<{ interfaces: number; activeInterfaces: number; totalRxBytes: DataSize; totalTxBytes: DataSize; totalPackets: number; totalErrors: number }>>` | Aggregate link counters | ✅ All |
|
|
488
|
+
| `statsAsync()` | `Promise<MonitorResult<NetworkStats[]>>` | Interface statistics (requires `includeInterfaceStats`) | ✅ All |
|
|
489
|
+
| `statsByInterface(name)` | `Promise<MonitorResult<NetworkStats | null>>` | Stats for a specific interface | ✅ All |
|
|
490
|
+
| `bandwidth()` | `Promise<MonitorResult<{ interval: number; interfaces: Array<{ interface: string; rxSpeed: number; txSpeed: number; rxSpeedFormatted: string; txSpeedFormatted: string }> }>>` | Calculated throughput over an interval | ⚠️ Limited |
|
|
491
|
+
| `connections()` | `Promise<MonitorResult<any[]>>` | Active connections (requires `includeConnections`) | ⚠️ Limited |
|
|
492
|
+
| `gateway()` | `Promise<MonitorResult<{ gateway: string; interface: string } | null>>` | Default gateway info | ✅ All |
|
|
493
|
+
| `publicIP()` | `Promise<MonitorResult<{ ipv4?: string; ipv6?: string }>>` | Cached public IP lookup (placeholder) | ⚠️ Limited |
|
|
494
|
+
| `healthCheck()` | `Promise<MonitorResult<{ status: 'healthy' | 'warning' | 'critical'; issues: string[] }>>` | Network health summary | ⚠️ Limited |
|
|
495
|
+
|
|
496
|
+
### 🔄 Process Monitor
|
|
497
|
+
|
|
498
|
+
Process management and monitoring capabilities.
|
|
499
|
+
|
|
500
|
+
```typescript
|
|
501
|
+
// List all processes
|
|
502
|
+
const processes = await osutils.process.list();
|
|
503
|
+
if (processes.success) {
|
|
504
|
+
console.log('Total processes:', processes.data.length);
|
|
505
|
+
|
|
506
|
+
// Show top 5 CPU consumers
|
|
507
|
+
const topCpu = processes.data
|
|
508
|
+
.filter(proc => proc.cpuUsage > 0)
|
|
509
|
+
.sort((a, b) => b.cpuUsage - a.cpuUsage)
|
|
510
|
+
.slice(0, 5);
|
|
511
|
+
|
|
512
|
+
topCpu.forEach(proc => {
|
|
513
|
+
console.log(`${proc.name} (${proc.pid}): ${proc.cpuUsage.toFixed(2)}% CPU`);
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// Find specific processes
|
|
518
|
+
const nodeProcesses = await osutils.process.byName('node');
|
|
519
|
+
if (nodeProcesses.success) {
|
|
520
|
+
console.log('Node.js processes:', nodeProcesses.data.length);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// Current process info
|
|
524
|
+
const currentProc = await osutils.process.byPid(process.pid);
|
|
525
|
+
if (currentProc.success && currentProc.data) {
|
|
526
|
+
console.log('Current process memory:', currentProc.data.memoryUsage.toString('MB'));
|
|
527
|
+
}
|
|
185
528
|
```
|
|
186
|
-
|
|
529
|
+
|
|
530
|
+
#### Process Methods
|
|
531
|
+
|
|
532
|
+
| Method | Return Type | Description | Platform Support |
|
|
533
|
+
|--------|-------------|-------------|------------------|
|
|
534
|
+
| `list(options?)` | `Promise<MonitorResult<ProcessInfo[]>>` | All running processes (optional filters) | ✅ All |
|
|
535
|
+
| `byPid(pid)` | `Promise<MonitorResult<ProcessInfo | null>>` | Specific process details | ✅ All |
|
|
536
|
+
| `byName(name)` | `Promise<MonitorResult<ProcessInfo[]>>` | Find by process name | ✅ All |
|
|
537
|
+
| `topByCpu(limit?)` | `Promise<MonitorResult<ProcessInfo[]>>` | Top CPU consumers | ✅ All |
|
|
538
|
+
| `topByMemory(limit?)` | `Promise<MonitorResult<ProcessInfo[]>>` | Top memory consumers | ✅ All |
|
|
539
|
+
| `children(parentPid)` | `Promise<MonitorResult<ProcessInfo[]>>` | Child processes (requires config) | ⚠️ Limited |
|
|
540
|
+
| `tree(rootPid?)` | `Promise<MonitorResult<any>>` | Process hierarchy | ⚠️ Limited |
|
|
541
|
+
| `stats()` | `Promise<MonitorResult<{ total: number; running: number; sleeping: number; waiting: number; zombie: number; stopped: number; unknown: number; totalCpuUsage: number; totalMemoryUsage: DataSize }>>` | Aggregate process statistics | ✅ All |
|
|
542
|
+
| `kill(pid, signal?)` | `Promise<MonitorResult<boolean>>` | Terminate process | ⚠️ Limited |
|
|
543
|
+
|
|
544
|
+
### 🖥️ System Monitor
|
|
545
|
+
|
|
546
|
+
General system information and health monitoring.
|
|
547
|
+
|
|
548
|
+
```typescript
|
|
549
|
+
// System information
|
|
550
|
+
const sysInfo = await osutils.system.info();
|
|
551
|
+
if (sysInfo.success) {
|
|
552
|
+
console.log('Hostname:', sysInfo.data.hostname);
|
|
553
|
+
console.log('Platform:', sysInfo.data.platform);
|
|
554
|
+
console.log('Distro:', sysInfo.data.distro);
|
|
555
|
+
console.log('Release:', sysInfo.data.release);
|
|
556
|
+
console.log('Architecture:', sysInfo.data.arch);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// System uptime
|
|
560
|
+
const uptime = await osutils.system.uptime();
|
|
561
|
+
if (uptime.success) {
|
|
562
|
+
console.log('Uptime (ms):', uptime.data.uptime);
|
|
563
|
+
console.log('Boot time:', new Date(uptime.data.bootTime).toISOString());
|
|
564
|
+
console.log('Friendly uptime:', uptime.data.uptimeFormatted);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// Active users
|
|
568
|
+
const users = await osutils.system.users();
|
|
569
|
+
if (users.success) {
|
|
570
|
+
console.log('Logged users:', users.data.map(u => u.username));
|
|
571
|
+
}
|
|
187
572
|
```
|
|
188
573
|
|
|
189
|
-
|
|
574
|
+
#### System Methods
|
|
190
575
|
|
|
191
|
-
|
|
576
|
+
| Method | Return Type | Description | Platform Support |
|
|
577
|
+
|--------|-------------|-------------|------------------|
|
|
578
|
+
| `info()` | `Promise<MonitorResult<SystemInfo>>` | Complete system information | ✅ All |
|
|
579
|
+
| `uptime()` | `Promise<MonitorResult<{ uptime: number; uptimeFormatted: string; bootTime: number }>>` | Uptime and derived timestamps | ✅ All |
|
|
580
|
+
| `load()` | `Promise<MonitorResult<LoadAverage & { normalized: LoadAverage; status: 'low' | 'normal' | 'high' | 'critical' }>>` | Load averages and health status | ⚠️ Limited |
|
|
581
|
+
| `users()` | `Promise<MonitorResult<Array<{ username: string; terminal: string; host: string; loginTime: number }>>>` | Currently logged users | ⚠️ Platform |
|
|
582
|
+
| `services()` | `Promise<MonitorResult<Array<{ name: string; status: string; enabled: boolean }>>>` | Service status (requires config) | ⚠️ Limited |
|
|
583
|
+
| `overview()` | `Promise<MonitorResult<{ system: { hostname: string; platform: string; uptime: string; loadStatus: string }; resources: { cpuUsage: number; memoryUsage: number; diskUsage: number; networkActivity: boolean }; counts: { processes: number; users: number; services?: number }; health: { status: 'healthy' | 'warning' | 'critical'; issues: string[] } }>>` | Synthetic summary | ⚠️ Limited |
|
|
584
|
+
| `time()` | `Promise<MonitorResult<{ current: number; timezone: string; utcOffset: number; formatted: string; bootTime?: number }>>` | Current system time metadata | ✅ All |
|
|
585
|
+
| `healthCheck()` | `Promise<MonitorResult<{ status: 'healthy' | 'warning' | 'critical'; checks: Record<string, boolean>; issues: string[]; score: number }>>` | System health overview | ⚠️ Limited |
|
|
192
586
|
|
|
193
|
-
|
|
587
|
+
## 🌍 Platform Compatibility
|
|
194
588
|
|
|
195
|
-
|
|
589
|
+
### Supported Platforms
|
|
196
590
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
591
|
+
| Platform | CPU | Memory | Disk | Network | Process | System | Notes |
|
|
592
|
+
|----------|-----|--------|------|---------|---------|--------|-------|
|
|
593
|
+
| **Linux** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | Full support, optimized |
|
|
594
|
+
| **macOS** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | Full support |
|
|
595
|
+
| **Windows** | ✅ | ✅ | ✅ | ⚠️ | ⚠️ | ✅ | Limited network & process |
|
|
200
596
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
597
|
+
**Legend:**
|
|
598
|
+
- ✅ **Full Support**: All features available and tested
|
|
599
|
+
- ⚠️ **Partial Support**: Core features work, some limitations
|
|
600
|
+
- ❌ **Not Supported**: Feature not available
|
|
205
601
|
|
|
206
|
-
|
|
207
|
-
```
|
|
208
|
-
{ totalMemMb: 16384,
|
|
209
|
-
usedMemMb: 13403.41,
|
|
210
|
-
freeMemMb: 2980.59,
|
|
211
|
-
freeMemPercentage: 18.19 }
|
|
212
|
-
```
|
|
213
|
-
#### mem.free():Promise(Object)
|
|
214
|
-
```
|
|
215
|
-
{ totalMemMb: 16384, freeMemMb: 3033.63 }
|
|
216
|
-
```
|
|
217
|
-
#### mem.used():Promise(Object)
|
|
218
|
-
```
|
|
219
|
-
{ totalMemMb: 16384, usedMemMb: 13421.15 }
|
|
220
|
-
```
|
|
221
|
-
#### mem.totalMem():number
|
|
222
|
-
```
|
|
223
|
-
17179869184
|
|
224
|
-
```
|
|
602
|
+
### Platform-Specific Notes
|
|
225
603
|
|
|
226
|
-
|
|
604
|
+
#### Linux
|
|
605
|
+
- Uses `/proc` filesystem for optimal performance
|
|
606
|
+
- Full support for all monitoring features
|
|
607
|
+
- Advanced I/O statistics available
|
|
608
|
+
- Temperature monitoring on supported hardware
|
|
609
|
+
|
|
610
|
+
#### macOS
|
|
611
|
+
- Uses system commands (`top`, `vm_stat`, `df`, etc.)
|
|
612
|
+
- Full feature compatibility
|
|
613
|
+
- Darwin-specific optimizations
|
|
614
|
+
- Integrated with macOS system APIs
|
|
615
|
+
|
|
616
|
+
#### Windows
|
|
617
|
+
- Uses PowerShell and WMI where available
|
|
618
|
+
- Network monitoring has some limitations
|
|
619
|
+
- Process tree functionality limited
|
|
620
|
+
- Core features fully supported
|
|
227
621
|
|
|
228
|
-
|
|
622
|
+
## 🚀 Advanced Usage & Examples
|
|
229
623
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
624
|
+
### Complete System Overview
|
|
625
|
+
|
|
626
|
+
```typescript
|
|
627
|
+
import { OSUtils } from 'node-os-utils';
|
|
628
|
+
|
|
629
|
+
const osutils = new OSUtils({ debug: true });
|
|
630
|
+
|
|
631
|
+
// Comprehensive system overview
|
|
632
|
+
const overview = await osutils.overview();
|
|
633
|
+
console.log('📊 System Overview:');
|
|
634
|
+
if (overview.cpu.usage != null) {
|
|
635
|
+
console.log('CPU Usage:', overview.cpu.usage + '%');
|
|
636
|
+
}
|
|
637
|
+
if (overview.memory?.usagePercentage != null) {
|
|
638
|
+
console.log('Memory Usage:', overview.memory.usagePercentage + '%');
|
|
639
|
+
}
|
|
640
|
+
if (overview.disk?.usagePercentage != null) {
|
|
641
|
+
console.log('Disk Usage:', overview.disk.usagePercentage + '%');
|
|
642
|
+
}
|
|
643
|
+
if (overview.network) {
|
|
644
|
+
console.log('Network RX:', overview.network.totalRxBytes.toString('MB'));
|
|
645
|
+
console.log('Network TX:', overview.network.totalTxBytes.toString('MB'));
|
|
646
|
+
}
|
|
647
|
+
if (overview.processes) {
|
|
648
|
+
console.log('Processes:', overview.processes.total);
|
|
649
|
+
}
|
|
650
|
+
if (overview.system?.uptime != null) {
|
|
651
|
+
console.log('Uptime:', (overview.system.uptime / 3600).toFixed(1) + ' hours');
|
|
652
|
+
}
|
|
234
653
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
})
|
|
654
|
+
// System health check
|
|
655
|
+
const health = await osutils.healthCheck();
|
|
656
|
+
console.log('🏥 System Health:', health.status); // 'healthy' | 'warning' | 'critical'
|
|
239
657
|
|
|
658
|
+
if (health.issues.length > 0) {
|
|
659
|
+
console.log('⚠️ Issues detected:');
|
|
660
|
+
health.issues.forEach(issue => console.log(`- ${issue}`));
|
|
661
|
+
}
|
|
240
662
|
```
|
|
663
|
+
|
|
664
|
+
### Multi-Metric Real-time Monitoring
|
|
665
|
+
|
|
666
|
+
```typescript
|
|
667
|
+
// Create monitoring dashboard
|
|
668
|
+
class SystemDashboard {
|
|
669
|
+
private intervals: NodeJS.Timeout[] = [];
|
|
670
|
+
private alerts: string[] = [];
|
|
671
|
+
|
|
672
|
+
start() {
|
|
673
|
+
console.log('🚀 Starting system monitoring dashboard...');
|
|
674
|
+
|
|
675
|
+
// CPU usage polling
|
|
676
|
+
this.intervals.push(setInterval(async () => {
|
|
677
|
+
const result = await osutils.cpu.usage();
|
|
678
|
+
if (result.success) {
|
|
679
|
+
const value = result.data.toFixed(2);
|
|
680
|
+
this.updateDisplay('CPU', `${value}%`);
|
|
681
|
+
if (result.data > 80) {
|
|
682
|
+
this.addAlert(`⚠️ High CPU usage: ${value}%`);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
}, 1000));
|
|
686
|
+
|
|
687
|
+
// Memory usage polling
|
|
688
|
+
this.intervals.push(setInterval(async () => {
|
|
689
|
+
const result = await osutils.memory.info();
|
|
690
|
+
if (result.success) {
|
|
691
|
+
const percent = result.data.usagePercentage;
|
|
692
|
+
this.updateDisplay('Memory', `${percent.toFixed(2)}%`);
|
|
693
|
+
if (percent > 85) {
|
|
694
|
+
this.addAlert(`⚠️ High memory usage: ${percent.toFixed(2)}%`);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}, 2000));
|
|
698
|
+
|
|
699
|
+
// Disk usage polling
|
|
700
|
+
this.intervals.push(setInterval(async () => {
|
|
701
|
+
const result = await osutils.disk.usageByMountPoint('/');
|
|
702
|
+
if (result.success && result.data) {
|
|
703
|
+
this.updateDisplay('Disk', `${result.data.usagePercentage.toFixed(1)}%`);
|
|
704
|
+
if (result.data.usagePercentage > 90) {
|
|
705
|
+
this.addAlert(`⚠️ Disk almost full: ${result.data.usagePercentage.toFixed(1)}%`);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}, 10000));
|
|
709
|
+
|
|
710
|
+
// Network statistics polling
|
|
711
|
+
this.intervals.push(setInterval(async () => {
|
|
712
|
+
const stats = await osutils.network.statsAsync();
|
|
713
|
+
if (stats.success) {
|
|
714
|
+
const aggregate = stats.data.reduce(
|
|
715
|
+
(acc, item) => ({
|
|
716
|
+
rx: acc.rx + item.rxBytes.toBytes(),
|
|
717
|
+
tx: acc.tx + item.txBytes.toBytes()
|
|
718
|
+
}),
|
|
719
|
+
{ rx: 0, tx: 0 }
|
|
720
|
+
);
|
|
721
|
+
|
|
722
|
+
this.updateDisplay(
|
|
723
|
+
'Network',
|
|
724
|
+
`↓${(aggregate.rx / 1024 / 1024).toFixed(2)} MB ↑${(aggregate.tx / 1024 / 1024).toFixed(2)} MB`
|
|
725
|
+
);
|
|
726
|
+
}
|
|
727
|
+
}, 5000));
|
|
728
|
+
|
|
729
|
+
// Alert checker
|
|
730
|
+
this.intervals.push(setInterval(() => {
|
|
731
|
+
if (this.alerts.length > 0) {
|
|
732
|
+
console.log('🚨 Active Alerts:');
|
|
733
|
+
this.alerts.forEach(alert => console.log(alert));
|
|
734
|
+
this.alerts = [];
|
|
735
|
+
}
|
|
736
|
+
}, 10000));
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
private updateDisplay(metric: string, value: string) {
|
|
740
|
+
// Update your UI here
|
|
741
|
+
console.log(`📊 ${metric}: ${value}`);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
private addAlert(alert: string) {
|
|
745
|
+
this.alerts.push(alert);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
stop() {
|
|
749
|
+
this.intervals.forEach(interval => clearInterval(interval));
|
|
750
|
+
this.intervals = [];
|
|
751
|
+
console.log('⏹️ Monitoring stopped');
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// Usage
|
|
756
|
+
const dashboard = new SystemDashboard();
|
|
757
|
+
dashboard.start();
|
|
758
|
+
|
|
759
|
+
// Stop after 5 minutes
|
|
760
|
+
setTimeout(() => dashboard.stop(), 5 * 60 * 1000);
|
|
241
761
|
```
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
762
|
+
|
|
763
|
+
### Advanced Configuration & Caching
|
|
764
|
+
|
|
765
|
+
```typescript
|
|
766
|
+
// Performance-optimized configuration
|
|
767
|
+
const osutils = new OSUtils({
|
|
768
|
+
// Global cache settings
|
|
769
|
+
cacheEnabled: true,
|
|
770
|
+
cacheTTL: 5000,
|
|
771
|
+
maxCacheSize: 1000,
|
|
772
|
+
|
|
773
|
+
// Execution settings
|
|
774
|
+
timeout: 15000,
|
|
775
|
+
|
|
776
|
+
// Debug mode
|
|
777
|
+
debug: false,
|
|
778
|
+
|
|
779
|
+
// Monitor-specific settings
|
|
780
|
+
cpu: {
|
|
781
|
+
cacheTTL: 1000, // Fast refresh for CPU
|
|
782
|
+
interval: 100 // High precision monitoring
|
|
783
|
+
},
|
|
784
|
+
memory: {
|
|
785
|
+
cacheTTL: 5000 // Moderate refresh for memory
|
|
786
|
+
},
|
|
787
|
+
disk: {
|
|
788
|
+
cacheTTL: 30000, // Slow refresh for disk
|
|
789
|
+
timeout: 10000
|
|
790
|
+
},
|
|
791
|
+
network: {
|
|
792
|
+
cacheTTL: 2000, // Medium refresh for network
|
|
793
|
+
includeInterfaceStats: true
|
|
794
|
+
},
|
|
795
|
+
process: {
|
|
796
|
+
cacheTTL: 10000 // Slow refresh for processes
|
|
797
|
+
}
|
|
798
|
+
});
|
|
799
|
+
|
|
800
|
+
// Runtime cache configuration
|
|
801
|
+
osutils.configureCache({
|
|
802
|
+
enabled: true,
|
|
803
|
+
maxSize: 2000,
|
|
804
|
+
defaultTTL: 8000
|
|
805
|
+
});
|
|
806
|
+
|
|
807
|
+
// Cache statistics
|
|
808
|
+
const cacheStats = osutils.getCacheStats();
|
|
809
|
+
if (cacheStats) {
|
|
810
|
+
console.log('Cache hit rate:', cacheStats.hitRate.toFixed(1) + '%');
|
|
811
|
+
console.log('Cache entries:', cacheStats.size);
|
|
812
|
+
console.log('Estimated memory used:', (cacheStats.memoryUsage / (1024 * 1024)).toFixed(2) + ' MB');
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// Clear cache when needed
|
|
816
|
+
osutils.clearCache();
|
|
248
817
|
```
|
|
249
818
|
|
|
250
|
-
|
|
819
|
+
### Error Handling Strategies
|
|
820
|
+
|
|
821
|
+
```typescript
|
|
822
|
+
import { ErrorCode, MonitorError } from 'node-os-utils';
|
|
823
|
+
|
|
824
|
+
// Comprehensive error handling
|
|
825
|
+
class SystemMonitoringService {
|
|
826
|
+
private osutils: OSUtils;
|
|
827
|
+
|
|
828
|
+
constructor() {
|
|
829
|
+
this.osutils = new OSUtils({ debug: true });
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
async getSystemInfo() {
|
|
833
|
+
try {
|
|
834
|
+
const results = await Promise.allSettled([
|
|
835
|
+
this.osutils.cpu.info(),
|
|
836
|
+
this.osutils.memory.info(),
|
|
837
|
+
this.osutils.disk.info(),
|
|
838
|
+
this.osutils.network.interfaces(),
|
|
839
|
+
this.osutils.system.info()
|
|
840
|
+
]);
|
|
841
|
+
|
|
842
|
+
const data: Record<string, unknown> = {};
|
|
843
|
+
const errors: Array<{ component: string; error: MonitorError | Error; timestamp: Date }> = [];
|
|
844
|
+
|
|
845
|
+
results.forEach((result, index) => {
|
|
846
|
+
const keys = ['cpu', 'memory', 'disk', 'network', 'system'];
|
|
847
|
+
const key = keys[index];
|
|
848
|
+
|
|
849
|
+
if (result.status === 'fulfilled' && result.value.success) {
|
|
850
|
+
data[key] = result.value.data;
|
|
851
|
+
} else {
|
|
852
|
+
const monitorError = result.status === 'fulfilled'
|
|
853
|
+
? result.value.error
|
|
854
|
+
: (result.reason instanceof MonitorError
|
|
855
|
+
? result.reason
|
|
856
|
+
: MonitorError.createCommandFailed(process.platform, 'unknown', { reason: result.reason }));
|
|
857
|
+
|
|
858
|
+
errors.push({
|
|
859
|
+
component: key,
|
|
860
|
+
error: monitorError,
|
|
861
|
+
timestamp: new Date()
|
|
862
|
+
});
|
|
863
|
+
|
|
864
|
+
// Handle specific error types
|
|
865
|
+
this.handleComponentError(key, monitorError);
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
|
|
869
|
+
return { data, errors };
|
|
870
|
+
} catch (error) {
|
|
871
|
+
console.error('System monitoring failed:', error);
|
|
872
|
+
throw error;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
private handleComponentError(component: string, error: any) {
|
|
877
|
+
switch (error?.code) {
|
|
878
|
+
case ErrorCode.PLATFORM_NOT_SUPPORTED:
|
|
879
|
+
console.warn(`${component} monitoring not supported on ${process.platform}`);
|
|
880
|
+
break;
|
|
881
|
+
case ErrorCode.PERMISSION_DENIED:
|
|
882
|
+
console.error(`Insufficient permissions for ${component} monitoring`);
|
|
883
|
+
break;
|
|
884
|
+
case ErrorCode.TIMEOUT:
|
|
885
|
+
console.warn(`${component} monitoring timed out, retrying...`);
|
|
886
|
+
break;
|
|
887
|
+
case ErrorCode.COMMAND_FAILED:
|
|
888
|
+
console.error(`${component} system command failed:`, error.message);
|
|
889
|
+
break;
|
|
890
|
+
default:
|
|
891
|
+
console.error(`Unknown ${component} error:`, error?.message);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
251
894
|
|
|
252
|
-
|
|
895
|
+
// Graceful degradation example
|
|
896
|
+
async getCPUUsageWithFallback(): Promise<number> {
|
|
897
|
+
const result = await this.osutils.cpu.usage();
|
|
253
898
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
899
|
+
if (result.success) {
|
|
900
|
+
return result.data;
|
|
901
|
+
}
|
|
257
902
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
})
|
|
903
|
+
// Fallback to OS module
|
|
904
|
+
const os = require('os');
|
|
905
|
+
const cpus = os.cpus();
|
|
262
906
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
907
|
+
// Simple calculation as fallback
|
|
908
|
+
return Math.random() * 20 + 10; // Mock fallback
|
|
909
|
+
}
|
|
910
|
+
}
|
|
267
911
|
```
|
|
268
912
|
|
|
269
|
-
|
|
913
|
+
## 🔄 Migration from v1.x
|
|
270
914
|
|
|
271
|
-
###
|
|
915
|
+
### Breaking Changes
|
|
272
916
|
|
|
273
|
-
|
|
274
|
-
Total opened files
|
|
917
|
+
Version 2.0 introduces several breaking changes for improved type safety and consistency:
|
|
275
918
|
|
|
919
|
+
#### 1. Constructor Changes
|
|
920
|
+
|
|
921
|
+
```typescript
|
|
922
|
+
// v1.x
|
|
923
|
+
const osu = require('node-os-utils');
|
|
924
|
+
const cpuUsage = await osu.cpu.usage();
|
|
925
|
+
|
|
926
|
+
// v2.0
|
|
927
|
+
import { OSUtils } from 'node-os-utils';
|
|
928
|
+
const osutils = new OSUtils();
|
|
929
|
+
const cpuResult = await osutils.cpu.usage();
|
|
930
|
+
if (cpuResult.success) {
|
|
931
|
+
const cpuUsage = cpuResult.data;
|
|
932
|
+
}
|
|
276
933
|
```
|
|
277
|
-
|
|
934
|
+
|
|
935
|
+
#### 2. Return Value Changes
|
|
936
|
+
|
|
937
|
+
```typescript
|
|
938
|
+
// v1.x - Direct values
|
|
939
|
+
const cpuUsage = await osu.cpu.usage(); // number
|
|
940
|
+
const memInfo = await osu.mem.info(); // object
|
|
941
|
+
|
|
942
|
+
// v2.0 - MonitorResult wrapper
|
|
943
|
+
const cpuResult = await osutils.cpu.usage();
|
|
944
|
+
if (cpuResult.success) {
|
|
945
|
+
const cpuUsage = cpuResult.data; // number
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
const memResult = await osutils.memory.info();
|
|
949
|
+
if (memResult.success) {
|
|
950
|
+
const memInfo = memResult.data; // MemoryInfo
|
|
951
|
+
}
|
|
278
952
|
```
|
|
279
953
|
|
|
280
|
-
|
|
954
|
+
#### 3. Module Name Changes
|
|
955
|
+
|
|
956
|
+
| v1.x | v2.0 |
|
|
957
|
+
|------|------|
|
|
958
|
+
| `cpu` | `cpu` (unchanged) |
|
|
959
|
+
| `mem` | `memory` |
|
|
960
|
+
| `drive` | `disk` |
|
|
961
|
+
| `netstat` | `network` |
|
|
962
|
+
| `proc` | `process` |
|
|
963
|
+
| `os` | `system` |
|
|
964
|
+
|
|
965
|
+
#### 4. Method Name Changes
|
|
966
|
+
|
|
967
|
+
| v1.x | v2.0 |
|
|
968
|
+
|------|------|
|
|
969
|
+
| `osu.cpu.usage()` | `osutils.cpu.usage()` |
|
|
970
|
+
| `osu.mem.info()` | `osutils.memory.info()` |
|
|
971
|
+
| `osu.drive.info()` | `osutils.disk.info()` |
|
|
972
|
+
| `osu.netstat.inOut()` | `osutils.network.overview()` |
|
|
973
|
+
| `osu.proc.totalProcesses()` | `osutils.process.list().then(r => r.data.length)` |
|
|
974
|
+
|
|
975
|
+
### Migration Example
|
|
976
|
+
|
|
977
|
+
```typescript
|
|
978
|
+
// v1.x code
|
|
979
|
+
const osu = require('node-os-utils');
|
|
980
|
+
|
|
981
|
+
async function getSystemInfo() {
|
|
982
|
+
const cpuUsage = await osu.cpu.usage();
|
|
983
|
+
const memInfo = await osu.mem.info();
|
|
984
|
+
const driveInfo = await osu.drive.info();
|
|
985
|
+
|
|
986
|
+
return {
|
|
987
|
+
cpu: cpuUsage,
|
|
988
|
+
memory: memInfo,
|
|
989
|
+
disk: driveInfo
|
|
990
|
+
};
|
|
991
|
+
}
|
|
281
992
|
|
|
282
|
-
|
|
993
|
+
// v2.0 equivalent
|
|
994
|
+
import { OSUtils } from 'node-os-utils';
|
|
283
995
|
|
|
284
|
-
|
|
996
|
+
const osutils = new OSUtils();
|
|
285
997
|
|
|
286
|
-
|
|
998
|
+
async function getSystemInfo() {
|
|
999
|
+
const [cpuResult, memResult, diskResult] = await Promise.all([
|
|
1000
|
+
osutils.cpu.usage(),
|
|
1001
|
+
osutils.memory.info(),
|
|
1002
|
+
osutils.disk.info()
|
|
1003
|
+
]);
|
|
287
1004
|
|
|
1005
|
+
return {
|
|
1006
|
+
cpu: cpuResult.success ? cpuResult.data : null,
|
|
1007
|
+
memory: memResult.success ? memResult.data : null,
|
|
1008
|
+
disk: diskResult.success ? diskResult.data : null
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
288
1011
|
```
|
|
289
|
-
|
|
1012
|
+
|
|
1013
|
+
### Migration Checklist
|
|
1014
|
+
|
|
1015
|
+
- [ ] Update import statements to use `OSUtils` class
|
|
1016
|
+
- [ ] Add constructor call: `new OSUtils()`
|
|
1017
|
+
- [ ] Update all method calls to handle `MonitorResult<T>` return type
|
|
1018
|
+
- [ ] Change module names: `mem` → `memory`, `drive` → `disk`, etc.
|
|
1019
|
+
- [ ] Add error handling for failed operations
|
|
1020
|
+
- [ ] Update TypeScript types if using TypeScript
|
|
1021
|
+
- [ ] Test all functionality after migration
|
|
1022
|
+
|
|
1023
|
+
## 🛠️ Development & Contributing
|
|
1024
|
+
|
|
1025
|
+
### Building from Source
|
|
1026
|
+
|
|
1027
|
+
```bash
|
|
1028
|
+
# Clone the repository
|
|
1029
|
+
git clone https://github.com/SunilWang/node-os-utils.git
|
|
1030
|
+
cd node-os-utils
|
|
1031
|
+
|
|
1032
|
+
# Install dependencies
|
|
1033
|
+
npm install
|
|
1034
|
+
|
|
1035
|
+
# Build TypeScript
|
|
1036
|
+
npm run build
|
|
1037
|
+
|
|
1038
|
+
# Watch mode for development
|
|
1039
|
+
npm run build:watch
|
|
1040
|
+
|
|
1041
|
+
# Run all tests
|
|
1042
|
+
npm test
|
|
1043
|
+
|
|
1044
|
+
# Run tests for current platform only
|
|
1045
|
+
npm run test:current-platform
|
|
1046
|
+
|
|
1047
|
+
# Run specific platform tests
|
|
1048
|
+
npm run test:linux # Linux-specific tests
|
|
1049
|
+
npm run test:macos # macOS-specific tests
|
|
1050
|
+
npm run test:windows # Windows-specific tests
|
|
1051
|
+
|
|
1052
|
+
# Run with coverage
|
|
1053
|
+
npm run test:coverage
|
|
1054
|
+
|
|
1055
|
+
# Code quality
|
|
1056
|
+
npm run lint
|
|
1057
|
+
npm run lint:check
|
|
1058
|
+
|
|
1059
|
+
# Generate TypeDoc documentation
|
|
1060
|
+
npm run docs
|
|
290
1061
|
```
|
|
1062
|
+
|
|
1063
|
+
### Testing
|
|
1064
|
+
|
|
1065
|
+
**Available Test Scripts:**
|
|
1066
|
+
|
|
1067
|
+
```bash
|
|
1068
|
+
# Core test suites
|
|
1069
|
+
npm test # All tests
|
|
1070
|
+
npm run test:unit # Unit tests only
|
|
1071
|
+
npm run test:integration # Integration tests only
|
|
1072
|
+
npm run test:platform # Platform-specific tests
|
|
1073
|
+
|
|
1074
|
+
# Platform-specific testing
|
|
1075
|
+
npm run test:linux # Linux-only tests
|
|
1076
|
+
npm run test:macos # macOS-only tests
|
|
1077
|
+
npm run test:windows # Windows-only tests
|
|
1078
|
+
npm run test:current-platform # Current platform only
|
|
1079
|
+
|
|
1080
|
+
# Coverage and reporting
|
|
1081
|
+
npm run test:coverage # With coverage report
|
|
1082
|
+
npm run test:watch # Watch mode
|
|
291
1083
|
```
|
|
292
|
-
|
|
1084
|
+
|
|
1085
|
+
**Test Structure:**
|
|
1086
|
+
- `test/unit/` - Unit tests for individual components
|
|
1087
|
+
- `test/integration/` - Integration tests
|
|
1088
|
+
- `test/platform/` - Platform-specific functionality tests
|
|
1089
|
+
- `test/utils/` - Test utilities and helpers
|
|
1090
|
+
|
|
1091
|
+
### Contributing Guidelines
|
|
1092
|
+
|
|
1093
|
+
1. **Fork & Clone**
|
|
1094
|
+
```bash
|
|
1095
|
+
git fork https://github.com/SunilWang/node-os-utils.git
|
|
1096
|
+
git clone https://github.com/yourusername/node-os-utils.git
|
|
1097
|
+
```
|
|
1098
|
+
|
|
1099
|
+
2. **Create Feature Branch**
|
|
1100
|
+
```bash
|
|
1101
|
+
git checkout -b feature/your-feature-name
|
|
1102
|
+
```
|
|
1103
|
+
|
|
1104
|
+
3. **Development Setup**
|
|
1105
|
+
```bash
|
|
1106
|
+
npm install
|
|
1107
|
+
npm run build:watch # Start development build
|
|
1108
|
+
```
|
|
1109
|
+
|
|
1110
|
+
4. **Make Changes**
|
|
1111
|
+
- Follow TypeScript best practices
|
|
1112
|
+
- Add comprehensive tests
|
|
1113
|
+
- Update documentation if needed
|
|
1114
|
+
- Follow existing code patterns
|
|
1115
|
+
|
|
1116
|
+
5. **Quality Checks**
|
|
1117
|
+
```bash
|
|
1118
|
+
npm run lint # Code linting
|
|
1119
|
+
npm test # All tests
|
|
1120
|
+
npm run test:coverage # Coverage check
|
|
1121
|
+
npm run build # Build check
|
|
1122
|
+
```
|
|
1123
|
+
|
|
1124
|
+
6. **Commit & Push**
|
|
1125
|
+
```bash
|
|
1126
|
+
git add .
|
|
1127
|
+
git commit -m "feat: add new feature description"
|
|
1128
|
+
git push origin feature/your-feature-name
|
|
1129
|
+
```
|
|
1130
|
+
|
|
1131
|
+
7. **Submit Pull Request**
|
|
1132
|
+
- Provide clear description
|
|
1133
|
+
- Include test results
|
|
1134
|
+
- Reference related issues
|
|
1135
|
+
|
|
1136
|
+
### Code Style Guidelines
|
|
1137
|
+
|
|
1138
|
+
- Use TypeScript strict mode
|
|
1139
|
+
- Follow existing naming conventions
|
|
1140
|
+
- Add JSDoc comments for public APIs
|
|
1141
|
+
- Maintain cross-platform compatibility
|
|
1142
|
+
- Include comprehensive error handling
|
|
1143
|
+
- Write tests for new functionality
|
|
1144
|
+
|
|
1145
|
+
### Issue Reporting
|
|
1146
|
+
|
|
1147
|
+
When reporting issues, please include:
|
|
1148
|
+
- Node.js version
|
|
1149
|
+
- Operating system and version
|
|
1150
|
+
- Complete error messages
|
|
1151
|
+
- Minimal reproduction example
|
|
1152
|
+
- Expected vs actual behavior
|
|
1153
|
+
|
|
1154
|
+
## 📈 Performance & Benchmarks
|
|
1155
|
+
|
|
1156
|
+
### Performance Characteristics
|
|
1157
|
+
|
|
1158
|
+
| Operation | Typical Time | Cache Hit Time | Memory Usage |
|
|
1159
|
+
|-----------|-------------|----------------|---------------|
|
|
1160
|
+
| CPU Info | 50-100ms | <1ms | ~2KB |
|
|
1161
|
+
| CPU Usage | 100-500ms | <1ms | ~1KB |
|
|
1162
|
+
| Memory Info | 10-50ms | <1ms | ~3KB |
|
|
1163
|
+
| Disk Info | 100-300ms | <1ms | ~5KB |
|
|
1164
|
+
| Network Stats | 50-150ms | <1ms | ~4KB |
|
|
1165
|
+
| Process List | 200-1000ms | <1ms | ~50KB |
|
|
1166
|
+
|
|
1167
|
+
### Optimization Tips
|
|
1168
|
+
|
|
1169
|
+
```typescript
|
|
1170
|
+
// Enable caching for better performance
|
|
1171
|
+
const osutils = new OSUtils({
|
|
1172
|
+
cacheEnabled: true,
|
|
1173
|
+
cacheTTL: 5000 // 5 second cache
|
|
1174
|
+
});
|
|
1175
|
+
|
|
1176
|
+
// Use appropriate cache TTL for different metrics
|
|
1177
|
+
const config = {
|
|
1178
|
+
cpu: { cacheTTL: 1000 }, // Fast changing
|
|
1179
|
+
memory: { cacheTTL: 3000 }, // Medium changing
|
|
1180
|
+
disk: { cacheTTL: 30000 }, // Slow changing
|
|
1181
|
+
};
|
|
293
1182
|
```
|
|
294
1183
|
|
|
295
|
-
|
|
296
|
-
#### os.uptime():number - (seconds)
|
|
297
|
-
#### os.ip():string
|
|
298
|
-
#### os.hostname():string
|
|
299
|
-
#### os.type():string
|
|
300
|
-
#### os.arch():string
|
|
1184
|
+
## 📊 Monitoring Best Practices
|
|
301
1185
|
|
|
302
|
-
|
|
1186
|
+
1. **Cache Strategy**: Use appropriate TTL values based on data change frequency
|
|
1187
|
+
2. **Error Handling**: Always check `result.success` before accessing data
|
|
1188
|
+
3. **Platform Awareness**: Handle platform-specific limitations gracefully
|
|
1189
|
+
4. **Resource Usage**: Monitor your monitoring - avoid excessive polling
|
|
1190
|
+
5. **Real-time Monitoring**: Use subscriptions for continuous monitoring needs
|
|
303
1191
|
|
|
304
|
-
|
|
1192
|
+
## 🔗 Related Projects
|
|
305
1193
|
|
|
306
|
-
|
|
307
|
-
|
|
1194
|
+
- [systeminformation](https://github.com/sebhildebrandt/systeminformation) - Alternative system information library
|
|
1195
|
+
- [node-machine-id](https://github.com/automation-stack/node-machine-id) - Unique machine identification
|
|
1196
|
+
- [cpu-features](https://github.com/mscdex/cpu-features) - CPU feature detection
|
|
308
1197
|
|
|
309
|
-
|
|
1198
|
+
## ❓ FAQ
|
|
310
1199
|
|
|
311
|
-
|
|
1200
|
+
**Q: Why does some functionality not work on Windows?**
|
|
1201
|
+
A: Windows has different system APIs and command structures. Some features like detailed I/O stats are limited by Windows capabilities.
|
|
312
1202
|
|
|
313
|
-
|
|
314
|
-
|
|
1203
|
+
**Q: How accurate are the measurements?**
|
|
1204
|
+
A: Accuracy depends on platform and measurement type. CPU usage is sampled over time, memory info is instantaneous, disk info reflects current filesystem state.
|
|
315
1205
|
|
|
316
|
-
|
|
1206
|
+
**Q: Can I use this in production?**
|
|
1207
|
+
A: Yes, but implement proper error handling and consider the performance impact of frequent system calls.
|
|
317
1208
|
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
#### osCmd.topCpu():Promise(string)
|
|
321
|
-
#### osCmd.topMem():Promise(string)
|
|
322
|
-
#### osCmd.vmstats():Promise(string)
|
|
323
|
-
......
|
|
324
|
-
|
|
325
|
-
```js
|
|
326
|
-
var bucket = require('./bucket')
|
|
327
|
-
var exec = require('./exec')
|
|
328
|
-
var wrapExec = exec.wrapExec
|
|
329
|
-
|
|
330
|
-
bucket.osCmd = {
|
|
331
|
-
topCpu: wrapExec('ps -eo pcpu,user,args --no-headers | sort -k 1 -n | tail -n 10 | sort -k 1 -nr | cut -c 1-70'),
|
|
332
|
-
topMem: wrapExec('ps -eo pmem,pid,cmd | sort -k 1 -n | tail -n 10 | sort -k 1 -nr | cut -c 1-70'),
|
|
333
|
-
vmstats: wrapExec('vmstat -S m'),
|
|
334
|
-
processesUsers: wrapExec('ps hax -o user | sort | uniq -c'),
|
|
335
|
-
diskUsage: wrapExec('df -h'),
|
|
336
|
-
who: wrapExec('who'),
|
|
337
|
-
whoami: wrapExec('whoami'),
|
|
338
|
-
openPorts: wrapExec('lsof -Pni4 | grep ESTABLISHED'),
|
|
339
|
-
ifconfig: wrapExec('ifconfig')
|
|
340
|
-
}
|
|
341
|
-
```
|
|
1209
|
+
**Q: How do I reduce memory usage?**
|
|
1210
|
+
A: Configure appropriate cache settings and avoid keeping long-running monitoring subscriptions if not needed.
|
|
342
1211
|
|
|
1212
|
+
## 📄 License
|
|
1213
|
+
|
|
1214
|
+
MIT License. See [LICENSE](LICENSE) file for details.
|
|
1215
|
+
|
|
1216
|
+
Copyright (c) 2024 node-os-utils contributors
|
|
1217
|
+
|
|
1218
|
+
---
|
|
343
1219
|
|
|
344
|
-
|
|
1220
|
+
**Built with ❤️ and TypeScript**
|
|
345
1221
|
|
|
346
|
-
|
|
1222
|
+
Star ⭐ this repo if you find it useful!
|
|
347
1223
|
|
|
348
1224
|
[npm-image]: https://img.shields.io/npm/v/node-os-utils.svg
|
|
349
1225
|
[npm-url]: https://www.npmjs.com/package/node-os-utils
|