node-os-utils 2.0.2 → 2.0.4

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.
Files changed (147) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README-zh.md +1291 -0
  3. package/README.md +28 -2
  4. package/dist/package.json +4 -2
  5. package/dist/src/adapters/linux-adapter.d.ts +17 -4
  6. package/dist/src/adapters/linux-adapter.d.ts.map +1 -1
  7. package/dist/src/adapters/linux-adapter.js +37 -12
  8. package/dist/src/adapters/linux-adapter.js.map +1 -1
  9. package/dist/src/adapters/macos-adapter.d.ts +17 -4
  10. package/dist/src/adapters/macos-adapter.d.ts.map +1 -1
  11. package/dist/src/adapters/macos-adapter.js +28 -11
  12. package/dist/src/adapters/macos-adapter.js.map +1 -1
  13. package/dist/src/adapters/windows-adapter.d.ts +13 -2
  14. package/dist/src/adapters/windows-adapter.d.ts.map +1 -1
  15. package/dist/src/adapters/windows-adapter.js +26 -3
  16. package/dist/src/adapters/windows-adapter.js.map +1 -1
  17. package/dist/src/monitors/cpu-monitor.d.ts.map +1 -1
  18. package/dist/src/monitors/cpu-monitor.js +7 -2
  19. package/dist/src/monitors/cpu-monitor.js.map +1 -1
  20. package/dist/src/monitors/process-monitor.d.ts +17 -4
  21. package/dist/src/monitors/process-monitor.d.ts.map +1 -1
  22. package/dist/src/monitors/process-monitor.js +30 -4
  23. package/dist/src/monitors/process-monitor.js.map +1 -1
  24. package/dist/src/types/config.d.ts +7 -0
  25. package/dist/src/types/config.d.ts.map +1 -1
  26. package/dist/src/utils/process-killer.d.ts +38 -0
  27. package/dist/src/utils/process-killer.d.ts.map +1 -0
  28. package/dist/src/utils/process-killer.js +96 -0
  29. package/dist/src/utils/process-killer.js.map +1 -0
  30. package/package.json +4 -2
  31. package/dist/.tsbuildinfo +0 -1
  32. package/dist/test/config/test-config.d.ts +0 -301
  33. package/dist/test/config/test-config.d.ts.map +0 -1
  34. package/dist/test/config/test-config.js +0 -235
  35. package/dist/test/config/test-config.js.map +0 -1
  36. package/dist/test/platform/linux.test.d.ts +0 -6
  37. package/dist/test/platform/linux.test.d.ts.map +0 -1
  38. package/dist/test/platform/linux.test.js +0 -307
  39. package/dist/test/platform/linux.test.js.map +0 -1
  40. package/dist/test/platform/macos.test.d.ts +0 -6
  41. package/dist/test/platform/macos.test.d.ts.map +0 -1
  42. package/dist/test/platform/macos.test.js +0 -276
  43. package/dist/test/platform/macos.test.js.map +0 -1
  44. package/dist/test/platform/windows.test.d.ts +0 -6
  45. package/dist/test/platform/windows.test.d.ts.map +0 -1
  46. package/dist/test/platform/windows.test.js +0 -320
  47. package/dist/test/platform/windows.test.js.map +0 -1
  48. package/dist/test/unit/adapters/adapter-factory.test.d.ts +0 -2
  49. package/dist/test/unit/adapters/adapter-factory.test.d.ts.map +0 -1
  50. package/dist/test/unit/adapters/adapter-factory.test.js +0 -147
  51. package/dist/test/unit/adapters/adapter-factory.test.js.map +0 -1
  52. package/dist/test/unit/adapters/linux-adapter.test.d.ts +0 -2
  53. package/dist/test/unit/adapters/linux-adapter.test.d.ts.map +0 -1
  54. package/dist/test/unit/adapters/linux-adapter.test.js +0 -204
  55. package/dist/test/unit/adapters/linux-adapter.test.js.map +0 -1
  56. package/dist/test/unit/adapters/macos-adapter.test.d.ts +0 -2
  57. package/dist/test/unit/adapters/macos-adapter.test.d.ts.map +0 -1
  58. package/dist/test/unit/adapters/macos-adapter.test.js +0 -237
  59. package/dist/test/unit/adapters/macos-adapter.test.js.map +0 -1
  60. package/dist/test/unit/adapters/windows-adapter.test.d.ts +0 -2
  61. package/dist/test/unit/adapters/windows-adapter.test.d.ts.map +0 -1
  62. package/dist/test/unit/adapters/windows-adapter.test.js +0 -111
  63. package/dist/test/unit/adapters/windows-adapter.test.js.map +0 -1
  64. package/dist/test/unit/core/base-monitor.test.d.ts +0 -2
  65. package/dist/test/unit/core/base-monitor.test.d.ts.map +0 -1
  66. package/dist/test/unit/core/base-monitor.test.js +0 -188
  67. package/dist/test/unit/core/base-monitor.test.js.map +0 -1
  68. package/dist/test/unit/core/cache-manager.test.d.ts +0 -6
  69. package/dist/test/unit/core/cache-manager.test.d.ts.map +0 -1
  70. package/dist/test/unit/core/cache-manager.test.js +0 -127
  71. package/dist/test/unit/core/cache-manager.test.js.map +0 -1
  72. package/dist/test/unit/core/platform-adapter.test.d.ts +0 -2
  73. package/dist/test/unit/core/platform-adapter.test.d.ts.map +0 -1
  74. package/dist/test/unit/core/platform-adapter.test.js +0 -186
  75. package/dist/test/unit/core/platform-adapter.test.js.map +0 -1
  76. package/dist/test/unit/index.test.d.ts +0 -2
  77. package/dist/test/unit/index.test.d.ts.map +0 -1
  78. package/dist/test/unit/index.test.js +0 -183
  79. package/dist/test/unit/index.test.js.map +0 -1
  80. package/dist/test/unit/monitors/cpu-monitor.test.d.ts +0 -2
  81. package/dist/test/unit/monitors/cpu-monitor.test.d.ts.map +0 -1
  82. package/dist/test/unit/monitors/cpu-monitor.test.js +0 -245
  83. package/dist/test/unit/monitors/cpu-monitor.test.js.map +0 -1
  84. package/dist/test/unit/monitors/disk-monitor.test.d.ts +0 -2
  85. package/dist/test/unit/monitors/disk-monitor.test.d.ts.map +0 -1
  86. package/dist/test/unit/monitors/disk-monitor.test.js +0 -46
  87. package/dist/test/unit/monitors/disk-monitor.test.js.map +0 -1
  88. package/dist/test/unit/monitors/memory-monitor.test.d.ts +0 -2
  89. package/dist/test/unit/monitors/memory-monitor.test.d.ts.map +0 -1
  90. package/dist/test/unit/monitors/memory-monitor.test.js +0 -142
  91. package/dist/test/unit/monitors/memory-monitor.test.js.map +0 -1
  92. package/dist/test/unit/monitors/network-monitor.test.d.ts +0 -2
  93. package/dist/test/unit/monitors/network-monitor.test.d.ts.map +0 -1
  94. package/dist/test/unit/monitors/network-monitor.test.js +0 -22
  95. package/dist/test/unit/monitors/network-monitor.test.js.map +0 -1
  96. package/dist/test/unit/monitors/process-monitor.test.d.ts +0 -2
  97. package/dist/test/unit/monitors/process-monitor.test.d.ts.map +0 -1
  98. package/dist/test/unit/monitors/process-monitor.test.js +0 -165
  99. package/dist/test/unit/monitors/process-monitor.test.js.map +0 -1
  100. package/dist/test/unit/monitors/system-monitor-macos.test.d.ts +0 -2
  101. package/dist/test/unit/monitors/system-monitor-macos.test.d.ts.map +0 -1
  102. package/dist/test/unit/monitors/system-monitor-macos.test.js +0 -115
  103. package/dist/test/unit/monitors/system-monitor-macos.test.js.map +0 -1
  104. package/dist/test/unit/monitors/system-monitor.test.d.ts +0 -2
  105. package/dist/test/unit/monitors/system-monitor.test.d.ts.map +0 -1
  106. package/dist/test/unit/monitors/system-monitor.test.js +0 -70
  107. package/dist/test/unit/monitors/system-monitor.test.js.map +0 -1
  108. package/dist/test/unit/types/common.test.d.ts +0 -6
  109. package/dist/test/unit/types/common.test.d.ts.map +0 -1
  110. package/dist/test/unit/types/common.test.js +0 -139
  111. package/dist/test/unit/types/common.test.js.map +0 -1
  112. package/dist/test/unit/types/config.test.d.ts +0 -2
  113. package/dist/test/unit/types/config.test.d.ts.map +0 -1
  114. package/dist/test/unit/types/config.test.js +0 -9
  115. package/dist/test/unit/types/config.test.js.map +0 -1
  116. package/dist/test/unit/types/errors.test.d.ts +0 -6
  117. package/dist/test/unit/types/errors.test.d.ts.map +0 -1
  118. package/dist/test/unit/types/errors.test.js +0 -184
  119. package/dist/test/unit/types/errors.test.js.map +0 -1
  120. package/dist/test/unit/types/index.test.d.ts +0 -2
  121. package/dist/test/unit/types/index.test.d.ts.map +0 -1
  122. package/dist/test/unit/types/index.test.js +0 -39
  123. package/dist/test/unit/types/index.test.js.map +0 -1
  124. package/dist/test/unit/types/monitors.test.d.ts +0 -2
  125. package/dist/test/unit/types/monitors.test.d.ts.map +0 -1
  126. package/dist/test/unit/types/monitors.test.js +0 -9
  127. package/dist/test/unit/types/monitors.test.js.map +0 -1
  128. package/dist/test/unit/types/platform.test.d.ts +0 -2
  129. package/dist/test/unit/types/platform.test.d.ts.map +0 -1
  130. package/dist/test/unit/types/platform.test.js +0 -9
  131. package/dist/test/unit/types/platform.test.js.map +0 -1
  132. package/dist/test/unit/utils/command-executor.test.d.ts +0 -6
  133. package/dist/test/unit/utils/command-executor.test.d.ts.map +0 -1
  134. package/dist/test/unit/utils/command-executor.test.js +0 -190
  135. package/dist/test/unit/utils/command-executor.test.js.map +0 -1
  136. package/dist/test/unit/utils/platform-specific.test.d.ts +0 -2
  137. package/dist/test/unit/utils/platform-specific.test.d.ts.map +0 -1
  138. package/dist/test/unit/utils/platform-specific.test.js +0 -32
  139. package/dist/test/unit/utils/platform-specific.test.js.map +0 -1
  140. package/dist/test/utils/platform-specific.d.ts +0 -139
  141. package/dist/test/utils/platform-specific.d.ts.map +0 -1
  142. package/dist/test/utils/platform-specific.js +0 -306
  143. package/dist/test/utils/platform-specific.js.map +0 -1
  144. package/dist/test/utils/test-base.d.ts +0 -157
  145. package/dist/test/utils/test-base.d.ts.map +0 -1
  146. package/dist/test/utils/test-base.js +0 -316
  147. package/dist/test/utils/test-base.js.map +0 -1
package/README-zh.md ADDED
@@ -0,0 +1,1291 @@
1
+ # node-os-utils v2.0
2
+
3
+ [![NPM 版本][npm-image]][npm-url]
4
+ [![NPM 下载量][downloads-image]][downloads-url]
5
+ [![TypeScript 支持](https://img.shields.io/badge/typescript-supported-blue.svg)](https://www.typescriptlang.org/)
6
+ [![Node.js 版本](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org/)
7
+ [![许可证: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+
9
+ 🚀 **版本 2.0** - 流行的 Node.js 操作系统监控库的完全重写版本。
10
+
11
+ **现代化的、TypeScript 原生的跨平台系统监控库**,提供全面的系统信息收集功能,具备智能缓存、事件驱动监控和强大的错误处理机制。
12
+
13
+ > **重大变更**: 这是一个包含破坏性变更的主要版本发布,与 v1.x 不兼容。
14
+
15
+ ## ✨ v2.0 新特性
16
+
17
+ ### 🎯 核心改进
18
+ - **🔧 TypeScript 优先**: 使用严格类型的完全重写版本
19
+ - **🏗️ 现代架构**: 使用适配器模式的清洁、模块化设计
20
+ - **⚡ 性能优化**: 带 TTL 管理的智能缓存系统
21
+ - **🛡️ 强大错误处理**: 具有详细错误码的一致错误处理
22
+ - **🔄 事件驱动**: 具有订阅管理的实时监控
23
+ - **📊 丰富数据类型**: 具有单位转换的全面数据结构
24
+ - **📆 时间线可追溯**: 系统信息新增 `bootTime` / `uptimeSeconds` 字段,Linux 进程指标补充精确的 `startTime`
25
+
26
+ ### 🌟 关键特性
27
+ - **🌍 跨平台**: Linux、macOS、Windows 支持,具有智能平台适配
28
+ - **📝 零依赖**: 仅使用内置模块的纯 Node.js 实现
29
+ - **⚙️ 可配置**: 缓存、超时和监控的灵活配置系统
30
+ - **🎯 类型安全**: 完整的 TypeScript 定义,支持 IntelliSense
31
+ - **🔍 全面**: CPU、内存、磁盘、网络、进程和系统监控
32
+ - **📈 实时**: 具有可自定义间隔的事件驱动监控
33
+ - **✅ 状态更精准**: 网络适配器保留原生接口状态,并在缺失时智能回退推断结果
34
+
35
+ ### 🧱 架构速览
36
+ - **AdapterFactory** 统一负责平台检测、适配器实例缓存,并提供 `getSupportedPlatforms()`、`checkPlatformCapabilities()` 等辅助工具。
37
+ - **CommandExecutor** 为不同系统提供统一的命令执行与错误封装,支持 `/bin/bash` → `/bin/sh`、PowerShell 自动降级等回退策略。
38
+ - **平台适配器** 封装操作系统特定实现(Linux 依赖 `/proc`,macOS 使用 `sysctl`/`powermetrics`,Windows 结合 PowerShell + WMI),并暴露自身支持的特性清单。
39
+ - **CacheManager** 提供基于 TTL 的智能缓存与 LRU 淘汰,显著降低高频监控时的系统开销。
40
+
41
+ ### 🖥️ 平台支持矩阵
42
+
43
+ | 功能 | Linux | macOS | Windows |
44
+ |------|:-----:|:-----:|:-------:|
45
+ | CPU 使用率 / 信息 | ✅ | ✅ | ✅ |
46
+ | CPU 温度 | ⚠️ 依赖 `/sys/class/thermal` | ⚠️ 需 `powermetrics`(sudo) | ❌ |
47
+ | 内存压力 | ⚠️ 需额外工具 | ✅ | ⚠️ WMI 估算 |
48
+ | 磁盘 I/O 指标 | ✅ | ✅ | ❌ |
49
+ | 网络统计 | ✅(`/proc/net/dev`) | ✅(`netstat -ib`) | ⚠️ PowerShell 需管理员 |
50
+ | 进程详情 | ✅ | ✅ | ✅(WMI) |
51
+ | 系统服务 | ⚠️ 依赖 `systemctl` | ❌ | ✅ |
52
+ | 容器兼容 | ⚠️ 自动检测并降级 | ⚠️ 自动检测并降级 | ⚠️ 自动检测并降级 |
53
+
54
+ > **图例**:✅ 完全支持 · ⚠️ 部分或受限 · ❌ 暂不支持
55
+
56
+ ### 🔍 能力自检
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('❗ 当前平台部分能力不可用:', report.issues);
73
+ }
74
+ ```
75
+
76
+ 需要进一步排查时,还可以调用 `AdapterFactory.getDebugInfo()` 查看适配器特性与系统命令可用性。
77
+
78
+ 在 **容器环境** 中库会自动:
79
+ - 通过 `/.dockerenv`、`/proc/1/cgroup` 或环境变量识别 Docker/Podman/Kubernetes;
80
+ - 检测到容器后禁用 `systemctl` 服务枚举,避免非 systemd 环境下报错;
81
+ - 当 `ss` 缺失时回退到 `netstat`,`ip` 缺失时回退到 `ifconfig`;
82
+ - 在返回的 `MonitorError` 中携带详细的主备命令错误,便于区分权限问题与真正的不支持;
83
+ - 通过 `adapter.getSupportedFeatures()` 保持特性标志同步,帮助监控器在功能不受支持时提前短路。
84
+
85
+ ## 🚀 安装
86
+
87
+ ```bash
88
+ npm install node-os-utils
89
+ ```
90
+
91
+ **系统要求:**
92
+ - Node.js 18.0.0 或更高版本
93
+ - 支持的操作系统: Linux、macOS、Windows
94
+
95
+ ## 🏁 快速开始
96
+
97
+ ### TypeScript
98
+
99
+ ```typescript
100
+ import { OSUtils } from 'node-os-utils';
101
+
102
+ const osutils = new OSUtils();
103
+
104
+ // 获取 CPU 使用率
105
+ const cpuUsage = await osutils.cpu.usage();
106
+ if (cpuUsage.success) {
107
+ console.log('CPU 使用率:', cpuUsage.data + '%');
108
+ }
109
+
110
+ // 获取内存信息
111
+ const memInfo = await osutils.memory.info();
112
+ if (memInfo.success) {
113
+ console.log('内存:', memInfo.data);
114
+ }
115
+
116
+ // 获取系统概览
117
+ const overview = await osutils.overview();
118
+ console.log('系统概览:', overview);
119
+ ```
120
+
121
+ ### JavaScript (CommonJS)
122
+
123
+ ```javascript
124
+ const { OSUtils } = require('node-os-utils');
125
+
126
+ const osutils = new OSUtils();
127
+
128
+ osutils.cpu.usage().then(result => {
129
+ if (result.success) {
130
+ console.log('CPU 使用率:', result.data + '%');
131
+ }
132
+ });
133
+ ```
134
+
135
+ ### 替代工厂函数
136
+
137
+ ```javascript
138
+ // 替代实例化方法
139
+ const { createOSUtils } = require('node-os-utils');
140
+
141
+ const osutils = createOSUtils({
142
+ cacheEnabled: true,
143
+ cacheTTL: 10000
144
+ });
145
+
146
+ // 与 OSUtils 类相同的 API
147
+ const cpuUsage = await osutils.cpu.usage();
148
+ ```
149
+
150
+ ## ⚙️ 配置
151
+
152
+ ### 全局配置
153
+
154
+ ```typescript
155
+ import { OSUtils } from 'node-os-utils';
156
+
157
+ const osutils = new OSUtils({
158
+ // 缓存设置
159
+ cacheEnabled: true,
160
+ cacheTTL: 5000,
161
+ maxCacheSize: 1000,
162
+
163
+ // 执行设置
164
+ timeout: 10000,
165
+
166
+ // 调试模式
167
+ debug: false,
168
+
169
+ // 监控器特定配置
170
+ cpu: {
171
+ cacheTTL: 30000,
172
+ // 是否将 iowait 从整体 CPU 使用率中排除(仅 Linux 生效)
173
+ // 默认 false:iowait 计入 overall,与传统监控工具行为一致
174
+ excludeIowait: false
175
+ },
176
+ memory: { cacheTTL: 5000 },
177
+ disk: { cacheTTL: 60000 }
178
+ });
179
+ ```
180
+
181
+ ### 监控器级别配置
182
+
183
+ ```typescript
184
+ // 配置单个监控器
185
+ const cpuMonitor = osutils.cpu
186
+ .withCaching(true, 30000)
187
+ .withConfig({ timeout: 5000 });
188
+
189
+ // 运行时配置缓存
190
+ osutils.configureCache({
191
+ enabled: true,
192
+ maxSize: 2000,
193
+ defaultTTL: 10000
194
+ });
195
+ ```
196
+
197
+ ## 🛡️ 错误处理
198
+
199
+ 所有操作都返回 `MonitorResult<T>` 对象,以保证一致的错误处理:
200
+
201
+ ```typescript
202
+ type MonitorResult<T> =
203
+ | {
204
+ success: true;
205
+ data: T;
206
+ timestamp: number;
207
+ cached: boolean;
208
+ platform: string;
209
+ }
210
+ | {
211
+ success: false;
212
+ error: MonitorError;
213
+ platform: string;
214
+ timestamp: number;
215
+ };
216
+ ```
217
+
218
+ ### 错误处理示例
219
+
220
+ ```typescript
221
+ const result = await osutils.cpu.info();
222
+
223
+ if (result.success) {
224
+ // 成功:使用 result.data
225
+ console.log('CPU 型号:', result.data.model);
226
+ console.log('核心数:', result.data.cores);
227
+ } else {
228
+ // 错误:优雅处理
229
+ console.error('错误:', result.error?.message);
230
+ console.error('错误代码:', result.error?.code);
231
+
232
+ // 平台特定处理
233
+ if (result.error?.code === ErrorCode.PLATFORM_NOT_SUPPORTED) {
234
+ console.log('此功能在', result.platform, '上不可用');
235
+ }
236
+ }
237
+ ```
238
+
239
+ ### 错误代码
240
+
241
+ ```typescript
242
+ enum ErrorCode {
243
+ PLATFORM_NOT_SUPPORTED = 'PLATFORM_NOT_SUPPORTED', // 当前平台不支持该功能
244
+ COMMAND_FAILED = 'COMMAND_FAILED', // 系统命令执行失败
245
+ PARSE_ERROR = 'PARSE_ERROR', // 命令输出或数据解析失败
246
+ PERMISSION_DENIED = 'PERMISSION_DENIED', // 权限不足无法完成操作
247
+ TIMEOUT = 'TIMEOUT', // 操作超过设定超时时间
248
+ INVALID_CONFIG = 'INVALID_CONFIG', // 提供的配置无效
249
+ NOT_AVAILABLE = 'NOT_AVAILABLE', // 指标暂时不可用
250
+ FILE_NOT_FOUND = 'FILE_NOT_FOUND', // 依赖的文件或路径不存在
251
+ NETWORK_ERROR = 'NETWORK_ERROR' // 网络操作失败
252
+ }
253
+ ```
254
+
255
+ ## 🛠️ 故障排查与权限提示
256
+
257
+ - **macOS 温度指标** 依赖 `powermetrics` 且需要管理员权限(`sudo powermetrics -n 1 -i 1000 --samplers smc`)。当命令不可用时,适配器会返回 `PLATFORM_NOT_SUPPORTED`。
258
+ - **Windows 网络 / 进程指标** 使用 PowerShell CIM 指令(`Get-NetAdapterStatistics`、`Get-CimInstance`),遇到 `PERMISSION_DENIED` 或 `COMMAND_FAILED` 建议在提升权限的 PowerShell 会话中运行。
259
+ - **Linux 命令回退**:大多数数据来自 `/proc`,若 `ip`、`ss` 等工具缺失,会自动回退到 `ifconfig`、`netstat`。你也可以提前通过 `osutils.checkPlatformCapabilities()` 验证依赖。
260
+ - 建议检查 `MonitorResult.error.code`,依据不同错误类型(超时、权限、平台不支持)给用户友好的提示。
261
+
262
+ ## 📚 完整 API 参考
263
+
264
+ ### 🔥 CPU 监控器
265
+
266
+ 全面的 CPU 监控,具有实时功能。
267
+
268
+ ```typescript
269
+ // 基本 CPU 信息
270
+ const cpuInfo = await osutils.cpu.info();
271
+ if (cpuInfo.success) {
272
+ console.log('型号:', cpuInfo.data.model);
273
+ console.log('核心数:', cpuInfo.data.cores);
274
+ console.log('架构:', cpuInfo.data.architecture);
275
+ }
276
+
277
+ // CPU 使用率监控
278
+ const cpuUsage = await osutils.cpu.usage();
279
+ if (cpuUsage.success) {
280
+ console.log('CPU 使用率:', cpuUsage.data + '%');
281
+ }
282
+
283
+ // 详细使用率(包含每核数据)
284
+ const usageDetails = await osutils.cpu.usageDetailed();
285
+ if (usageDetails.success) {
286
+ console.log('整体使用率:', usageDetails.data.overall);
287
+ console.log('各核心使用率:', usageDetails.data.cores);
288
+ }
289
+
290
+ // 负载平均值(Linux/macOS)
291
+ const loadAvg = await osutils.cpu.loadAverage();
292
+ if (loadAvg.success) {
293
+ console.log('负载平均值:', loadAvg.data);
294
+ }
295
+ ```
296
+
297
+ #### CPU 方法
298
+
299
+ | 方法 | 返回类型 | 描述 | 平台支持 |
300
+ |--------|-------------|-------------|------------------|
301
+ | `info()` | `Promise<MonitorResult<CPUInfo>>` | CPU 型号、核心、线程、架构 | ✅ 全部 |
302
+ | `usage()` | `Promise<MonitorResult<number>>` | CPU 使用率百分比 (0-100) | ✅ 全部 |
303
+ | `usageDetailed()` | `Promise<MonitorResult<CPUUsage>>` | 详细使用率(含每核心) | ✅ 全部 |
304
+ | `usageByCore()` | `Promise<MonitorResult<number[]>>` | 每核心使用率数组 | ✅ 全部 |
305
+ | `loadAverage()` | `Promise<MonitorResult<LoadAverage>>` | 负载平均值 (1, 5, 15 分钟) | ✅ Linux/macOS |
306
+ | `temperature()` | `Promise<MonitorResult<Temperature[]>>` | CPU 温度传感器 | ⚠️ 有限 |
307
+ | `frequency()` | `Promise<MonitorResult<FrequencyInfo[]>>` | 当前 CPU 频率信息 | ⚠️ 有限 |
308
+ | `getCacheInfo()` | `Promise<MonitorResult<any>>` | CPU 缓存层级信息 | ⚠️ 有限 |
309
+ | `coreCount()` | `Promise<MonitorResult<{ physical: number; logical: number }>>` | 物理/逻辑核心数量 | ✅ 全部 |
310
+
311
+ #### CPU 配置项
312
+
313
+ | 配置项 | 类型 | 默认值 | 说明 |
314
+ |--------|------|--------|------|
315
+ | `excludeIowait` | `boolean` | `false` | 为 `true` 时,I/O 等待时间(iowait)将从 `overall` 使用率中剔除,适合 I/O 密集型场景下避免 CPU 使用率虚高。`iowait` 仍作为独立字段在 `usageDetailed()` 中返回。仅 Linux 生效。 |
316
+
317
+ ```typescript
318
+ // 在 I/O 密集型 Linux 环境中排除 iowait
319
+ const osutils = new OSUtils({
320
+ cpu: { excludeIowait: true }
321
+ });
322
+
323
+ const result = await osutils.cpu.usageDetailed();
324
+ if (result.success) {
325
+ console.log('整体使用率(不含 iowait):', result.data.overall + '%');
326
+ console.log('iowait:', result.data.iowait + '%'); // 仍可单独读取
327
+ }
328
+ ```
329
+
330
+ #### 实时 CPU 监控
331
+
332
+ ```typescript
333
+ // 每秒轮询一次使用率
334
+ const pollInterval = setInterval(async () => {
335
+ const result = await osutils.cpu.usage();
336
+ if (result.success) {
337
+ console.log(`CPU 使用率: ${result.data.toFixed(2)}%`);
338
+ if (result.data > 80) {
339
+ console.warn('⚠️ 检测到高 CPU 使用率!');
340
+ }
341
+ }
342
+ }, 1000);
343
+
344
+ setTimeout(() => {
345
+ clearInterval(pollInterval);
346
+ console.log('CPU 使用率轮询已停止');
347
+ }, 30000);
348
+
349
+ // 使用 monitor() 获取 CPU 基本信息快照
350
+ const cpuInfoSubscription = osutils.cpu.withCaching(false).monitor(5000, (info) => {
351
+ console.log('CPU 型号:', info.model);
352
+ });
353
+
354
+ setTimeout(() => cpuInfoSubscription.unsubscribe(), 20000);
355
+ ```
356
+
357
+ ### 💾 内存监控器
358
+
359
+ 带智能单位转换的详细内存信息。
360
+
361
+ ```typescript
362
+ // 带 DataSize 帮助方法的内存信息
363
+ const memInfo = await osutils.memory.info();
364
+ if (memInfo.success) {
365
+ console.log('总内存:', memInfo.data.total.toGB().toFixed(2) + ' GB');
366
+ console.log('可用:', memInfo.data.available.toGB().toFixed(2) + ' GB');
367
+ console.log('已用:', memInfo.data.used.toGB().toFixed(2) + ' GB');
368
+ console.log('使用率:', memInfo.data.usagePercentage.toFixed(2) + '%');
369
+ }
370
+
371
+ // 快速内存使用率百分比
372
+ const memUsage = await osutils.memory.usage();
373
+ if (memUsage.success) {
374
+ console.log('内存使用率:', memUsage.data.toFixed(2) + '%');
375
+ }
376
+
377
+ // 摘要视图
378
+ const memSummary = await osutils.memory.summary();
379
+ if (memSummary.success) {
380
+ console.log('摘要:', memSummary.data);
381
+ }
382
+ ```
383
+
384
+ #### 内存方法
385
+
386
+ | 方法 | 返回类型 | 描述 | 平台支持 |
387
+ |--------|-------------|-------------|------------------|
388
+ | `info()` | `Promise<MonitorResult<MemoryInfo>>` | 带 DataSize 对象的详细内存分解 | ✅ 全部 |
389
+ | `detailed()` | `Promise<MonitorResult<MemoryInfo & { breakdown: Record<string, unknown> }>>` | 含平台特定明细 | ⚠️ 平台 |
390
+ | `usage()` | `Promise<MonitorResult<number>>` | 内存使用率百分比 (0-100) | ✅ 全部 |
391
+ | `available()` | `Promise<MonitorResult<DataSize>>` | 可用内存量 | ✅ 全部 |
392
+ | `swap()` | `Promise<MonitorResult<SwapInfo>>` | 虚拟内存/交换信息 | ✅ 全部 |
393
+ | `pressure()` | `Promise<MonitorResult<MemoryPressure>>` | 内存压力指标 | ⚠️ 有限 |
394
+ | `summary()` | `Promise<MonitorResult<{ total: string; used: string; available: string; usagePercentage: number; swap: { total: string; used: string; usagePercentage: number } }>>` | 友好的汇总结果 | ✅ 全部 |
395
+
396
+ #### DataSize 对象
397
+
398
+ ```typescript
399
+ class DataSize {
400
+ constructor(bytes: number);
401
+ toBytes(): number;
402
+ toKB(): number;
403
+ toMB(): number;
404
+ toGB(): number;
405
+ toTB(): number;
406
+ toString(unit?: 'auto' | 'B' | 'KB' | 'MB' | 'GB' | 'TB'): string;
407
+ }
408
+
409
+ // 使用示例
410
+ const memory = await osutils.memory.info();
411
+ if (memory.success) {
412
+ console.log(memory.data.total.toString('GB')); // "16.00 GB"
413
+ console.log(memory.data.available.toString()); // 自动选择单位
414
+ }
415
+ ```
416
+
417
+ ### 💽 磁盘监控器
418
+
419
+ 全面的磁盘和存储监控。
420
+
421
+ ```typescript
422
+ // 所有磁盘信息
423
+ const diskInfo = await osutils.disk.info();
424
+ if (diskInfo.success) {
425
+ diskInfo.data.forEach(disk => {
426
+ console.log('文件系统:', disk.filesystem);
427
+ console.log('挂载点:', disk.mountpoint);
428
+ console.log('总容量:', disk.total.toString('GB'));
429
+ console.log('可用:', disk.available.toString('GB'));
430
+ console.log('使用率:', disk.usagePercentage + '%');
431
+ });
432
+ }
433
+
434
+ // 指定挂载点的使用情况
435
+ const rootUsage = await osutils.disk.usageByMountPoint('/');
436
+ if (rootUsage.success && rootUsage.data) {
437
+ console.log('根目录使用率:', rootUsage.data.usagePercentage + '%');
438
+ }
439
+
440
+ // I/O 统计
441
+ const ioStats = await osutils.disk.stats();
442
+ if (ioStats.success) {
443
+ ioStats.data.forEach(stat => {
444
+ console.log(`${stat.device}:`, {
445
+ readBytes: stat.readBytes.toString('MB'),
446
+ writeBytes: stat.writeBytes.toString('MB'),
447
+ readCount: stat.readCount,
448
+ writeCount: stat.writeCount
449
+ });
450
+ });
451
+ }
452
+ ```
453
+
454
+ #### 磁盘方法
455
+
456
+ | 方法 | 返回类型 | 描述 | 平台支持 |
457
+ |--------|-------------|-------------|------------------|
458
+ | `info()` | `Promise<MonitorResult<DiskInfo[]>>` | 磁盘 / 分区信息 | ✅ 全部 |
459
+ | `infoByDevice(device)` | `Promise<MonitorResult<DiskInfo | null>>` | 按设备或挂载点查询 | ✅ 全部 |
460
+ | `usage()` | `Promise<MonitorResult<DiskUsage[]>>` | 所有挂载点的使用情况 | ✅ 全部 |
461
+ | `usageByMountPoint(mountPoint)` | `Promise<MonitorResult<DiskUsage | null>>` | 指定挂载点使用情况 | ✅ 全部 |
462
+ | `overallUsage()` | `Promise<MonitorResult<number>>` | 所有磁盘加权平均使用率 | ✅ 全部 |
463
+ | `stats()` | `Promise<MonitorResult<DiskStats[]>>` | I/O 统计摘要(需 `includeStats`) | ⚠️ 有限 |
464
+ | `mounts()` | `Promise<MonitorResult<MountPoint[]>>` | 挂载点配置详情 | ✅ 全部 |
465
+ | `filesystems()` | `Promise<MonitorResult<FileSystem[]>>` | 支持的文件系统类型 | ✅ 全部 |
466
+ | `spaceOverview()` | `Promise<MonitorResult<{ total: DataSize; used: DataSize; available: DataSize; usagePercentage: number; disks: number }>>` | 聚合空间使用情况 | ✅ 全部 |
467
+ | `healthCheck()` | `Promise<MonitorResult<{ status: 'healthy' | 'warning' | 'critical'; issues: string[] }>>` | 基础磁盘健康检查 | ⚠️ 有限 |
468
+
469
+ ### 🌐 网络监控器
470
+
471
+ 网络接口和流量监控。
472
+
473
+ ```typescript
474
+ // 网络接口
475
+ const interfaces = await osutils.network.interfaces();
476
+ if (interfaces.success) {
477
+ interfaces.data.forEach(iface => {
478
+ console.log('接口:', iface.name);
479
+ console.log('地址:', iface.addresses);
480
+ console.log('状态:', iface.state);
481
+ });
482
+ }
483
+
484
+ // 网络总览
485
+ const overview = await osutils.network.overview();
486
+ if (overview.success) {
487
+ console.log('总接收:', overview.data.totalRxBytes.toString('MB'));
488
+ console.log('总发送:', overview.data.totalTxBytes.toString('MB'));
489
+ }
490
+
491
+ // 接口统计信息
492
+ const stats = await osutils.network.statsAsync();
493
+ if (stats.success) {
494
+ stats.data.forEach(stat => {
495
+ console.log(`${stat.interface}: RX ${stat.rxBytes.toString('MB')} | TX ${stat.txBytes.toString('MB')}`);
496
+ });
497
+ }
498
+
499
+ // 实时接口监控(返回接口快照)
500
+ const netSub = osutils.network.monitor(5000, (snapshot) => {
501
+ const active = snapshot.filter(iface => iface.state === 'up').map(iface => iface.name);
502
+ console.log('活跃接口:', active);
503
+ });
504
+ ```
505
+
506
+ #### 网络方法
507
+
508
+ | 方法 | 返回类型 | 描述 | 平台支持 |
509
+ |--------|-------------|-------------|------------------|
510
+ | `interfaces()` | `Promise<MonitorResult<NetworkInterface[]>>` | 所有网络接口 | ✅ 全部 |
511
+ | `interfaceByName(name)` | `Promise<MonitorResult<NetworkInterface | null>>` | 指定接口信息 | ✅ 全部 |
512
+ | `overview()` | `Promise<MonitorResult<{ interfaces: number; activeInterfaces: number; totalRxBytes: DataSize; totalTxBytes: DataSize; totalPackets: number; totalErrors: number }>>` | 网络统计总览 | ✅ 全部 |
513
+ | `statsAsync()` | `Promise<MonitorResult<NetworkStats[]>>` | 接口统计(需 `includeInterfaceStats`) | ✅ 全部 |
514
+ | `statsByInterface(name)` | `Promise<MonitorResult<NetworkStats | null>>` | 指定接口统计 | ✅ 全部 |
515
+ | `bandwidth()` | `Promise<MonitorResult<{ interval: number; interfaces: Array<{ interface: string; rxSpeed: number; txSpeed: number; rxSpeedFormatted: string; txSpeedFormatted: string }> }>>` | 带宽测量(两次采样) | ⚠️ 有限 |
516
+ | `connections()` | `Promise<MonitorResult<any[]>>` | 活动连接(需启用 `includeConnections`) | ⚠️ 有限 |
517
+ | `gateway()` | `Promise<MonitorResult<{ gateway: string; interface: string } | null>>` | 默认网关信息 | ✅ 全部 |
518
+ | `publicIP()` | `Promise<MonitorResult<{ ipv4?: string; ipv6?: string }>>` | 公网 IP(占位实现) | ⚠️ 有限 |
519
+ | `healthCheck()` | `Promise<MonitorResult<{ status: 'healthy' | 'warning' | 'critical'; issues: string[] }>>` | 网络健康检查 | ⚠️ 有限 |
520
+
521
+ ### 🔄 进程监控器
522
+
523
+ 进程管理和监控功能。
524
+
525
+ ```typescript
526
+ // 列出所有进程
527
+ const processes = await osutils.process.list();
528
+ if (processes.success) {
529
+ console.log('总进程数:', processes.data.length);
530
+
531
+ // 显示前 5 个 CPU 消耗者
532
+ const topCpu = processes.data
533
+ .filter(proc => proc.cpuUsage > 0)
534
+ .sort((a, b) => b.cpuUsage - a.cpuUsage)
535
+ .slice(0, 5);
536
+
537
+ topCpu.forEach(proc => {
538
+ console.log(`${proc.name} (${proc.pid}): ${proc.cpuUsage.toFixed(2)}% CPU`);
539
+ });
540
+ }
541
+
542
+ // 查找特定进程
543
+ const nodeProcesses = await osutils.process.byName('node');
544
+ if (nodeProcesses.success) {
545
+ console.log('Node.js 进程数:', nodeProcesses.data.length);
546
+ }
547
+
548
+ // 当前进程信息
549
+ const currentProc = await osutils.process.byPid(process.pid);
550
+ if (currentProc.success && currentProc.data) {
551
+ console.log('当前进程内存:', currentProc.data.memoryUsage.toString('MB'));
552
+ }
553
+ ```
554
+
555
+ #### 进程方法
556
+
557
+ | 方法 | 返回类型 | 描述 | 平台支持 |
558
+ |--------|-------------|-------------|------------------|
559
+ | `list(options?)` | `Promise<MonitorResult<ProcessInfo[]>>` | 所有运行进程(支持过滤) | ✅ 全部 |
560
+ | `byPid(pid)` | `Promise<MonitorResult<ProcessInfo | null>>` | 特定进程详细信息 | ✅ 全部 |
561
+ | `byName(name)` | `Promise<MonitorResult<ProcessInfo[]>>` | 按进程名查找 | ✅ 全部 |
562
+ | `topByCpu(limit?)` | `Promise<MonitorResult<ProcessInfo[]>>` | 顶级 CPU 消耗者 | ✅ 全部 |
563
+ | `topByMemory(limit?)` | `Promise<MonitorResult<ProcessInfo[]>>` | 顶级内存消耗者 | ✅ 全部 |
564
+ | `children(parentPid)` | `Promise<MonitorResult<ProcessInfo[]>>` | 子进程列表(需启用配置) | ⚠️ 有限 |
565
+ | `tree(rootPid?)` | `Promise<MonitorResult<any>>` | 进程层次结构 | ⚠️ 有限 |
566
+ | `stats()` | `Promise<MonitorResult<{ total: number; running: number; sleeping: number; waiting: number; zombie: number; stopped: number; unknown: number; totalCpuUsage: number; totalMemoryUsage: DataSize }>>` | 进程统计汇总 | ✅ 全部 |
567
+ | `kill(pid, signal?)` | `Promise<MonitorResult<boolean>>` | 使用校验后的信号终止数字 PID | ⚠️ 有限 |
568
+
569
+ 所有基于 PID 的进程查询都会先校验运行时参数,再调用平台命令。`kill()` 支持 `TERM` / `SIGTERM` 等信号名称或十进制信号编号。运行时参数非法时返回 `data: false`,且参数不会传入 shell。Unix 的 `kill()` 保留 PID `0` / 负数对应的原生进程组语义;Windows 要求正整数 PID,并将 `SIGKILL` / `KILL` / `9` 映射为强制 `taskkill`。
570
+
571
+ ### 🖥️ 系统监控器
572
+
573
+ 通用系统信息和健康监控。
574
+
575
+ ```typescript
576
+ // 系统信息
577
+ const sysInfo = await osutils.system.info();
578
+ if (sysInfo.success) {
579
+ console.log('主机名:', sysInfo.data.hostname);
580
+ console.log('平台:', sysInfo.data.platform);
581
+ console.log('发行版:', sysInfo.data.distro);
582
+ console.log('版本:', sysInfo.data.release);
583
+ console.log('架构:', sysInfo.data.arch);
584
+ }
585
+
586
+ // 系统运行时间
587
+ const uptime = await osutils.system.uptime();
588
+ if (uptime.success) {
589
+ console.log('运行时间 (毫秒):', uptime.data.uptime);
590
+ console.log('启动时间:', new Date(uptime.data.bootTime).toISOString());
591
+ console.log('格式化运行时间:', uptime.data.uptimeFormatted);
592
+ }
593
+
594
+ // 活动用户
595
+ const users = await osutils.system.users();
596
+ if (users.success) {
597
+ console.log('登录用户:', users.data.map(u => u.username));
598
+ }
599
+ ```
600
+
601
+ #### 系统方法
602
+
603
+ | 方法 | 返回类型 | 描述 | 平台支持 |
604
+ |--------|-------------|-------------|------------------|
605
+ | `info()` | `Promise<MonitorResult<SystemInfo>>` | 完整的系统信息 | ✅ 全部 |
606
+ | `uptime()` | `Promise<MonitorResult<{ uptime: number; uptimeFormatted: string; bootTime: number }>>` | 运行时间与启动时间戳 | ✅ 全部 |
607
+ | `load()` | `Promise<MonitorResult<LoadAverage & { normalized: LoadAverage; status: 'low' | 'normal' | 'high' | 'critical' }>>` | 系统负载与状态 | ⚠️ 有限 |
608
+ | `users()` | `Promise<MonitorResult<Array<{ username: string; terminal: string; host: string; loginTime: number }>>>` | 当前登录用户 | ⚠️ 平台 |
609
+ | `services()` | `Promise<MonitorResult<Array<{ name: string; status: string; enabled: boolean }>>>` | 服务状态(需配置开启) | ⚠️ 有限 |
610
+ | `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[] } }>>` | 综合概览 | ⚠️ 有限 |
611
+ | `time()` | `Promise<MonitorResult<{ current: number; timezone: string; utcOffset: number; formatted: string; bootTime?: number }>>` | 当前时间信息 | ✅ 全部 |
612
+ | `healthCheck()` | `Promise<MonitorResult<{ status: 'healthy' | 'warning' | 'critical'; checks: Record<string, boolean>; issues: string[]; score: number }>>` | 系统健康报告 | ⚠️ 有限 |
613
+
614
+ ## 🌍 平台兼容性
615
+
616
+ ### 支持的平台
617
+
618
+ | 平台 | CPU | 内存 | 磁盘 | 网络 | 进程 | 系统 | 注释 |
619
+ |----------|-----|--------|------|---------|---------|--------|---------|
620
+ | **Linux** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 完全支持,已优化 |
621
+ | **macOS** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 完全支持 |
622
+ | **Windows** | ✅ | ✅ | ✅ | ⚠️ | ⚠️ | ✅ | 网络和进程功能有限 |
623
+
624
+ **图例:**
625
+ - ✅ **完全支持**: 所有功能可用并经过测试
626
+ - ⚠️ **部分支持**: 核心功能工作,有一些限制
627
+ - ❌ **不支持**: 功能不可用
628
+
629
+ ### 平台特定说明
630
+
631
+ #### Linux
632
+ - 使用 `/proc` 文件系统以获得最佳性能
633
+ - 对所有监控功能完全支持
634
+ - 提供高级 I/O 统计
635
+ - 支持硬件上的温度监控
636
+
637
+ #### macOS
638
+ - 使用系统命令(`top`、`vm_stat`、`df` 等)
639
+ - 完全功能兼容性
640
+ - Darwin 特定优化
641
+ - 与 macOS 系统 API 集成
642
+
643
+ #### Windows
644
+ - 可用时使用 PowerShell 和 WMI
645
+ - 网络监控有一些限制
646
+ - 进程树功能有限
647
+ - 核心功能完全支持
648
+
649
+ ## 🚀 高级用法和示例
650
+
651
+ ### 完整系统概览
652
+
653
+ ```typescript
654
+ import { OSUtils } from 'node-os-utils';
655
+
656
+ const osutils = new OSUtils({ debug: true });
657
+
658
+ // 全面系统概览
659
+ const overview = await osutils.overview();
660
+ console.log('📊 系统概览:');
661
+ if (overview.cpu.usage != null) {
662
+ console.log('CPU 使用率:', overview.cpu.usage + '%');
663
+ }
664
+ if (overview.memory?.usagePercentage != null) {
665
+ console.log('内存使用率:', overview.memory.usagePercentage + '%');
666
+ }
667
+ if (overview.disk?.usagePercentage != null) {
668
+ console.log('磁盘使用率:', overview.disk.usagePercentage + '%');
669
+ }
670
+ if (overview.network) {
671
+ console.log('网络接收:', overview.network.totalRxBytes.toString('MB'));
672
+ console.log('网络发送:', overview.network.totalTxBytes.toString('MB'));
673
+ }
674
+ if (overview.processes) {
675
+ console.log('进程数:', overview.processes.total);
676
+ }
677
+ if (overview.system?.uptime != null) {
678
+ console.log('运行时间:', (overview.system.uptime / 3600).toFixed(1) + ' 小时');
679
+ }
680
+
681
+ // 系统健康检查
682
+ const health = await osutils.healthCheck();
683
+ console.log('🏥 系统健康:', health.status); // 'healthy' | 'warning' | 'critical'
684
+
685
+ if (health.issues.length > 0) {
686
+ console.log('⚠️ 检测到问题:');
687
+ health.issues.forEach(issue => console.log(`- ${issue}`));
688
+ }
689
+ ```
690
+
691
+ ### 多指标实时监控
692
+
693
+ ```typescript
694
+ // 创建监控仪表板
695
+ class SystemDashboard {
696
+ private intervals: NodeJS.Timeout[] = [];
697
+ private alerts: string[] = [];
698
+
699
+ start() {
700
+ console.log('🚀 启动系统监控仪表板...');
701
+
702
+ // CPU 使用率轮询
703
+ this.intervals.push(setInterval(async () => {
704
+ const result = await osutils.cpu.usage();
705
+ if (result.success) {
706
+ const value = result.data.toFixed(2);
707
+ this.updateDisplay('CPU', `${value}%`);
708
+ if (result.data > 80) {
709
+ this.addAlert(`⚠️ 高 CPU 使用率: ${value}%`);
710
+ }
711
+ }
712
+ }, 1000));
713
+
714
+ // 内存使用率轮询
715
+ this.intervals.push(setInterval(async () => {
716
+ const result = await osutils.memory.info();
717
+ if (result.success) {
718
+ const percent = result.data.usagePercentage;
719
+ this.updateDisplay('内存', `${percent.toFixed(2)}%`);
720
+ if (percent > 85) {
721
+ this.addAlert(`⚠️ 高内存使用率: ${percent.toFixed(2)}%`);
722
+ }
723
+ }
724
+ }, 2000));
725
+
726
+ // 磁盘使用率轮询
727
+ this.intervals.push(setInterval(async () => {
728
+ const result = await osutils.disk.usageByMountPoint('/');
729
+ if (result.success && result.data) {
730
+ const percent = result.data.usagePercentage;
731
+ this.updateDisplay('磁盘', `${percent.toFixed(1)}%`);
732
+ if (percent > 90) {
733
+ this.addAlert(`⚠️ 磁盘几乎已满: ${percent.toFixed(1)}%`);
734
+ }
735
+ }
736
+ }, 10000));
737
+
738
+ // 网络统计轮询
739
+ this.intervals.push(setInterval(async () => {
740
+ const stats = await osutils.network.statsAsync();
741
+ if (stats.success) {
742
+ const aggregate = stats.data.reduce(
743
+ (acc, item) => ({
744
+ rx: acc.rx + item.rxBytes.toBytes(),
745
+ tx: acc.tx + item.txBytes.toBytes()
746
+ }),
747
+ { rx: 0, tx: 0 }
748
+ );
749
+
750
+ this.updateDisplay(
751
+ '网络',
752
+ `↓${(aggregate.rx / 1024 / 1024).toFixed(2)} MB ↑${(aggregate.tx / 1024 / 1024).toFixed(2)} MB`
753
+ );
754
+ }
755
+ }, 5000));
756
+
757
+ // 警报检查器
758
+ this.intervals.push(setInterval(() => {
759
+ if (this.alerts.length > 0) {
760
+ console.log('🚨 活动警报:');
761
+ this.alerts.forEach(alert => console.log(alert));
762
+ this.alerts = [];
763
+ }
764
+ }, 10000));
765
+ }
766
+
767
+ private updateDisplay(metric: string, value: string) {
768
+ // 在这里更新您的 UI
769
+ console.log(`📊 ${metric}: ${value}`);
770
+ }
771
+
772
+ private addAlert(alert: string) {
773
+ this.alerts.push(alert);
774
+ }
775
+
776
+ stop() {
777
+ this.intervals.forEach(interval => clearInterval(interval));
778
+ this.intervals = [];
779
+ console.log('⏹️ 监控已停止');
780
+ }
781
+ }
782
+
783
+ // 使用
784
+ const dashboard = new SystemDashboard();
785
+ dashboard.start();
786
+
787
+ // 5 分钟后停止
788
+ setTimeout(() => dashboard.stop(), 5 * 60 * 1000);
789
+ ```
790
+
791
+ ### 高级配置和缓存
792
+
793
+ ```typescript
794
+ // 性能优化配置
795
+ const osutils = new OSUtils({
796
+ // 全局缓存设置
797
+ cacheEnabled: true,
798
+ cacheTTL: 5000,
799
+ maxCacheSize: 1000,
800
+
801
+ // 执行设置
802
+ timeout: 15000,
803
+
804
+ // 调试模式
805
+ debug: false,
806
+
807
+ // 监控器特定设置
808
+ cpu: {
809
+ cacheTTL: 1000, // CPU 快速刷新
810
+ interval: 100 // 高精度监控
811
+ },
812
+ memory: {
813
+ cacheTTL: 5000 // 内存中等刷新
814
+ },
815
+ disk: {
816
+ cacheTTL: 30000, // 磁盘慢速刷新
817
+ timeout: 10000
818
+ },
819
+ network: {
820
+ cacheTTL: 2000, // 网络中等刷新
821
+ includeInterfaceStats: true
822
+ },
823
+ process: {
824
+ cacheTTL: 10000 // 进程慢速刷新
825
+ }
826
+ });
827
+
828
+ // 运行时缓存配置
829
+ osutils.configureCache({
830
+ enabled: true,
831
+ maxSize: 2000,
832
+ defaultTTL: 8000
833
+ });
834
+
835
+ // 缓存统计
836
+ const cacheStats = osutils.getCacheStats();
837
+ if (cacheStats) {
838
+ console.log('缓存命中率:', cacheStats.hitRate.toFixed(1) + '%');
839
+ console.log('缓存条目数:', cacheStats.size);
840
+ console.log('估算内存使用:', (cacheStats.memoryUsage / (1024 * 1024)).toFixed(2) + ' MB');
841
+ }
842
+
843
+ // 需要时清理缓存
844
+ osutils.clearCache();
845
+ ```
846
+
847
+ ### 错误处理策略
848
+
849
+ ```typescript
850
+ import { ErrorCode, MonitorError } from 'node-os-utils';
851
+
852
+ // 全面错误处理
853
+ class SystemMonitoringService {
854
+ private osutils: OSUtils;
855
+
856
+ constructor() {
857
+ this.osutils = new OSUtils({ debug: true });
858
+ }
859
+
860
+ async getSystemInfo() {
861
+ try {
862
+ const results = await Promise.allSettled([
863
+ this.osutils.cpu.info(),
864
+ this.osutils.memory.info(),
865
+ this.osutils.disk.info(),
866
+ this.osutils.network.interfaces(),
867
+ this.osutils.system.info()
868
+ ]);
869
+
870
+ const data: Record<string, unknown> = {};
871
+ const errors: Array<{ component: string; error: MonitorError | Error; timestamp: Date }> = [];
872
+
873
+ results.forEach((result, index) => {
874
+ const keys = ['cpu', 'memory', 'disk', 'network', 'system'];
875
+ const key = keys[index];
876
+
877
+ if (result.status === 'fulfilled' && result.value.success) {
878
+ data[key] = result.value.data;
879
+ } else {
880
+ const monitorError = result.status === 'fulfilled'
881
+ ? result.value.error
882
+ : (result.reason instanceof MonitorError
883
+ ? result.reason
884
+ : MonitorError.createCommandFailed(process.platform, 'unknown', { reason: result.reason }));
885
+
886
+ errors.push({
887
+ component: key,
888
+ error: monitorError,
889
+ timestamp: new Date()
890
+ });
891
+
892
+ // 处理特定错误类型
893
+ this.handleComponentError(key, monitorError);
894
+ }
895
+ });
896
+
897
+ return { data, errors };
898
+ } catch (error) {
899
+ console.error('系统监控失败:', error);
900
+ throw error;
901
+ }
902
+ }
903
+
904
+ private handleComponentError(component: string, error: any) {
905
+ switch (error?.code) {
906
+ case ErrorCode.PLATFORM_NOT_SUPPORTED:
907
+ console.warn(`${component} 监控在 ${process.platform} 上不受支持`);
908
+ break;
909
+ case ErrorCode.PERMISSION_DENIED:
910
+ console.error(`${component} 监控权限不足`);
911
+ break;
912
+ case ErrorCode.TIMEOUT:
913
+ console.warn(`${component} 监控超时,正在重试...`);
914
+ break;
915
+ case ErrorCode.COMMAND_FAILED:
916
+ console.error(`${component} 系统命令失败:`, error.message);
917
+ break;
918
+ default:
919
+ console.error(`未知 ${component} 错误:`, error?.message);
920
+ }
921
+ }
922
+
923
+ // 优雅降级示例
924
+ async getCPUUsageWithFallback(): Promise<number> {
925
+ const result = await this.osutils.cpu.usage();
926
+
927
+ if (result.success) {
928
+ return result.data;
929
+ }
930
+
931
+ // 回退到 OS 模块
932
+ const os = require('os');
933
+ const cpus = os.cpus();
934
+
935
+ // 作为回退的简单计算
936
+ return Math.random() * 20 + 10; // 模拟回退
937
+ }
938
+ }
939
+ ```
940
+
941
+ ## 🔄 从 v1.x 迁移到 2.0
942
+
943
+ ### 重大变更
944
+
945
+ 版本 2.0 引入了一些重大变更,以提高类型安全性和一致性:
946
+
947
+ #### 1. 构造函数变更
948
+
949
+ ```typescript
950
+ // v1.x
951
+ const osu = require('node-os-utils');
952
+ const cpuUsage = await osu.cpu.usage();
953
+
954
+ // v2.0
955
+ import { OSUtils } from 'node-os-utils';
956
+ const osutils = new OSUtils();
957
+ const cpuResult = await osutils.cpu.usage();
958
+ if (cpuResult.success) {
959
+ const cpuUsage = cpuResult.data;
960
+ }
961
+ ```
962
+
963
+ #### 2. 返回值变更
964
+
965
+ ```typescript
966
+ // v1.x - 直接值
967
+ const cpuUsage = await osu.cpu.usage(); // number
968
+ const memInfo = await osu.mem.info(); // object
969
+
970
+ // v2.0 - MonitorResult 包装器
971
+ const cpuResult = await osutils.cpu.usage();
972
+ if (cpuResult.success) {
973
+ const cpuUsage = cpuResult.data; // number
974
+ }
975
+
976
+ const memResult = await osutils.memory.info();
977
+ if (memResult.success) {
978
+ const memInfo = memResult.data; // MemoryInfo
979
+ }
980
+ ```
981
+
982
+ #### 3. 模块名称变更
983
+
984
+ | v1.x | v2.0 |
985
+ |------|------|
986
+ | `cpu` | `cpu` (不变) |
987
+ | `mem` | `memory` |
988
+ | `drive` | `disk` |
989
+ | `netstat` | `network` |
990
+ | `proc` | `process` |
991
+ | `os` | `system` |
992
+
993
+ #### 4. 方法名称变更
994
+
995
+ | v1.x | v2.0 |
996
+ |------|------|
997
+ | `osu.cpu.usage()` | `osutils.cpu.usage()` |
998
+ | `osu.mem.info()` | `osutils.memory.info()` |
999
+ | `osu.drive.info()` | `osutils.disk.info()` |
1000
+ | `osu.netstat.inOut()` | `osutils.network.overview()` |
1001
+ | `osu.proc.totalProcesses()` | `osutils.process.list().then(r => r.data.length)` |
1002
+
1003
+ ### 迁移示例
1004
+
1005
+ ```typescript
1006
+ // v1.x 代码
1007
+ const osu = require('node-os-utils');
1008
+
1009
+ async function getSystemInfo() {
1010
+ const cpuUsage = await osu.cpu.usage();
1011
+ const memInfo = await osu.mem.info();
1012
+ const driveInfo = await osu.drive.info();
1013
+
1014
+ return {
1015
+ cpu: cpuUsage,
1016
+ memory: memInfo,
1017
+ disk: driveInfo
1018
+ };
1019
+ }
1020
+
1021
+ // v2.0 等效代码
1022
+ import { OSUtils } from 'node-os-utils';
1023
+
1024
+ const osutils = new OSUtils();
1025
+
1026
+ async function getSystemInfo() {
1027
+ const [cpuResult, memResult, diskResult] = await Promise.all([
1028
+ osutils.cpu.usage(),
1029
+ osutils.memory.info(),
1030
+ osutils.disk.info()
1031
+ ]);
1032
+
1033
+ return {
1034
+ cpu: cpuResult.success ? cpuResult.data : null,
1035
+ memory: memResult.success ? memResult.data : null,
1036
+ disk: diskResult.success ? diskResult.data : null
1037
+ };
1038
+ }
1039
+ ```
1040
+
1041
+ ### 迁移清单
1042
+
1043
+ - [ ] 更新导入语句以使用 `OSUtils` 类
1044
+ - [ ] 添加构造函数调用:`new OSUtils()`
1045
+ - [ ] 更新所有方法调用以处理 `MonitorResult<T>` 返回类型
1046
+ - [ ] 更改模块名称:`mem` → `memory`、`drive` → `disk` 等
1047
+ - [ ] 为失败操作添加错误处理
1048
+ - [ ] 如果使用 TypeScript,更新 TypeScript 类型
1049
+ - [ ] 迁移后测试所有功能
1050
+
1051
+ ## 🛠️ 开发和贡献
1052
+
1053
+ ### 从源码构建
1054
+
1055
+ ```bash
1056
+ # 克隆仓库
1057
+ git clone https://github.com/SunilWang/node-os-utils.git
1058
+ cd node-os-utils
1059
+
1060
+ # 安装依赖
1061
+ npm install
1062
+
1063
+ # 构建 TypeScript
1064
+ npm run build
1065
+
1066
+ # 监控模式开发
1067
+ npm run build:watch
1068
+
1069
+ # 运行所有测试
1070
+ npm test
1071
+
1072
+ # 仅运行当前平台测试
1073
+ npm run test:current-platform
1074
+
1075
+ # 运行特定平台测试
1076
+ npm run test:linux # Linux 特定测试
1077
+ npm run test:macos # macOS 特定测试
1078
+ npm run test:windows # Windows 特定测试
1079
+
1080
+ # 带覆盖率运行
1081
+ npm run test:coverage
1082
+
1083
+ # 代码质量
1084
+ npm run lint
1085
+ npm run lint:check
1086
+
1087
+ # 生成 TypeDoc 文档
1088
+ npm run docs
1089
+ ```
1090
+
1091
+ ### 测试
1092
+
1093
+ **可用的测试脚本:**
1094
+
1095
+ ```bash
1096
+ # 核心测试套件
1097
+ npm test # 所有测试
1098
+ npm run test:unit # 仅单元测试
1099
+ npm run test:integration # 仅集成测试
1100
+ npm run test:platform # 平台特定测试
1101
+
1102
+ # 平台特定测试
1103
+ npm run test:linux # 仅 Linux 测试
1104
+ npm run test:macos # 仅 macOS 测试
1105
+ npm run test:windows # 仅 Windows 测试
1106
+ npm run test:current-platform # 仅当前平台
1107
+
1108
+ # 覆盖率和报告
1109
+ npm run test:coverage # 带覆盖率报告
1110
+ npm run test:watch # 监控模式
1111
+ ```
1112
+
1113
+ **测试结构:**
1114
+ - `test/unit/` - 单个组件的单元测试
1115
+ - `test/integration/` - 集成测试
1116
+ - `test/platform/` - 平台特定功能测试
1117
+ - `test/utils/` - 测试工具和助手
1118
+
1119
+ ### 贡献指南
1120
+
1121
+ 1. **Fork 和克隆**
1122
+ ```bash
1123
+ git fork https://github.com/SunilWang/node-os-utils.git
1124
+ git clone https://github.com/yourusername/node-os-utils.git
1125
+ ```
1126
+
1127
+ 2. **创建功能分支**
1128
+ ```bash
1129
+ git checkout -b feature/your-feature-name
1130
+ ```
1131
+
1132
+ 3. **开发设置**
1133
+ ```bash
1134
+ npm install
1135
+ npm run build:watch # 启动开发构建
1136
+ ```
1137
+
1138
+ 4. **进行更改**
1139
+ - 遵循 TypeScript 最佳实践
1140
+ - 添加全面测试
1141
+ - 必要时更新文档
1142
+ - 遵循现有代码模式
1143
+
1144
+ 5. **质量检查**
1145
+ ```bash
1146
+ npm run lint # 代码检查
1147
+ npm test # 所有测试
1148
+ npm run test:coverage # 覆盖率检查
1149
+ npm run build # 构建检查
1150
+ ```
1151
+
1152
+ 6. **提交和推送**
1153
+ ```bash
1154
+ git add .
1155
+ git commit -m "feat: add new feature description"
1156
+ git push origin feature/your-feature-name
1157
+ ```
1158
+
1159
+ 7. **提交拉取请求**
1160
+ - 提供清晰的描述
1161
+ - 包含测试结果
1162
+ - 引用相关问题
1163
+
1164
+ ### 代码风格指南
1165
+
1166
+ - 使用 TypeScript 严格模式
1167
+ - 遵循现有命名约定
1168
+ - 为公共 API 添加 JSDoc 注释
1169
+ - 维护跨平台兼容性
1170
+ - 包含全面的错误处理
1171
+ - 为新功能编写测试
1172
+
1173
+ ### 问题报告
1174
+
1175
+ 报告问题时,请包含:
1176
+ - Node.js 版本
1177
+ - 操作系统和版本
1178
+ - 完整的错误消息
1179
+ - 最小复现示例
1180
+ - 预期与实际行为
1181
+
1182
+ ## 📈 性能和基准测试
1183
+
1184
+ ### 性能特征
1185
+
1186
+ | 操作 | 典型时间 | 缓存命中时间 | 内存使用 |
1187
+ |-----------|-------------|----------------|---------------|
1188
+ | CPU 信息 | 50-100ms | <1ms | ~2KB |
1189
+ | CPU 使用率 | 100-500ms | <1ms | ~1KB |
1190
+ | 内存信息 | 10-50ms | <1ms | ~3KB |
1191
+ | 磁盘信息 | 100-300ms | <1ms | ~5KB |
1192
+ | 网络统计 | 50-150ms | <1ms | ~4KB |
1193
+ | 进程列表 | 200-1000ms | <1ms | ~50KB |
1194
+
1195
+ ### 优化提示
1196
+
1197
+ ```typescript
1198
+ // 启用缓存以获得更好性能
1199
+ const osutils = new OSUtils({
1200
+ cacheEnabled: true,
1201
+ cacheTTL: 5000 // 5 秒缓存
1202
+ });
1203
+
1204
+ // 为不同指标使用适当的缓存 TTL
1205
+ const config = {
1206
+ cpu: { cacheTTL: 1000 }, // 快速变化
1207
+ memory: { cacheTTL: 3000 }, // 中等变化
1208
+ disk: { cacheTTL: 30000 }, // 缓慢变化
1209
+ };
1210
+ ```
1211
+
1212
+ ## 📊 监控最佳实践
1213
+
1214
+ 1. **缓存策略**: 根据数据变化频率使用适当的 TTL 值
1215
+ 2. **错误处理**: 始终在访问数据前检查 `result.success`
1216
+ 3. **平台感知**: 优雅地处理平台特定限制
1217
+ 4. **资源使用**: 监控您的监控 - 避免过度轮询
1218
+ 5. **实时监控**: 对于持续监控需求使用订阅
1219
+
1220
+ ## 🔗 相关项目
1221
+
1222
+ - [systeminformation](https://github.com/sebhildebrandt/systeminformation) - 替代系统信息库
1223
+ - [node-machine-id](https://github.com/automation-stack/node-machine-id) - 唯一机器标识
1224
+ - [cpu-features](https://github.com/mscdex/cpu-features) - CPU 特性检测
1225
+
1226
+ ## 🦕 Deno 兼容性
1227
+
1228
+ `node-os-utils` 支持在 Deno 的 Node.js 兼容层(`deno run --node-modules-dir`)下运行。当 Deno 的兼容层无法执行原生 shell 命令(如 Windows 上的 PowerShell),库会**优雅降级**而非抛出异常:
1229
+
1230
+ | 操作 | 降级行为 |
1231
+ |------|---------|
1232
+ | `cpu.info()` | 降级到 `os.cpus()` 基础数据 |
1233
+ | `memory.info()` | 降级到 `os.totalmem()` / `os.freemem()` 基础数据 |
1234
+ | `disk.info()`、`network.stats()`、`process.list()` | 返回 `success: false` 的 `MonitorResult` |
1235
+
1236
+ 首次降级时会输出一次性警告:
1237
+
1238
+ ```
1239
+ [node-os-utils] cpu degraded: Windows PowerShell/WMI unavailable, falling back to os.cpus() data. Some features may not be available in the current runtime environment.
1240
+ ```
1241
+
1242
+ **示例:**
1243
+ ```ts
1244
+ // deno run --allow-read --allow-env --allow-sys app.ts
1245
+ import { createOSUtils } from 'node-os-utils';
1246
+
1247
+ const utils = createOSUtils();
1248
+ const cpu = await utils.cpu.info();
1249
+ if (cpu.success) {
1250
+ console.log(cpu.data.threads); // Deno 下也能正常工作
1251
+ } else {
1252
+ console.log('CPU 信息不可用:', cpu.error.message);
1253
+ }
1254
+ ```
1255
+
1256
+ ## 特性标志同步说明
1257
+
1258
+ 当监控器启用降级模式时,适配器的 `getSupportedFeatures()` 返回的特性标志可能仍显示 `true`,
1259
+ 但实际上某些功能已降级。建议在捕获到 `MonitorResult.success === false` 时以结果为准,
1260
+ 而非依赖特性标志进行预检查。
1261
+
1262
+ ## ❓ 常见问题
1263
+
1264
+ **问:为什么某些功能在 Windows 上不工作?**
1265
+ 答:Windows 具有不同的系统 API 和命令结构。一些功能如详细的 I/O 统计受到 Windows 能力的限制。
1266
+
1267
+ **问:测量的准确性如何?**
1268
+ 答:准确性取决于平台和测量类型。CPU 使用率是随时间采样的,内存信息是瞬时的,磁盘信息反映当前文件系统状态。
1269
+
1270
+ **问:可以在生产环境中使用吗?**
1271
+ 答:可以,但要实现适当的错误处理,并考虑频繁系统调用的性能影响。
1272
+
1273
+ **问:如何减少内存使用?**
1274
+ 答:配置适当的缓存设置,并在不需要时避免保持长时间运行的监控订阅。
1275
+
1276
+ ## 📄 许可证
1277
+
1278
+ MIT 许可证。详细信息请参阅 [LICENSE](LICENSE) 文件。
1279
+
1280
+ Copyright (c) 2024 node-os-utils 贡献者
1281
+
1282
+ ---
1283
+
1284
+ **用 ❤️ 和 TypeScript 构建**
1285
+
1286
+ 如果您觉得这个仓库有用,请给个星标 ⭐!
1287
+
1288
+ [npm-image]: https://img.shields.io/npm/v/node-os-utils.svg
1289
+ [npm-url]: https://www.npmjs.com/package/node-os-utils
1290
+ [downloads-image]: https://img.shields.io/npm/dt/node-os-utils.svg
1291
+ [downloads-url]: https://npmjs.org/package/node-os-utils