[![NPM 版本][npm-image]][npm-url]
[![NPM 下载量][downloads-image]][downloads-url]
🚀 版本 2.0 - 流行的 Node.js 操作系统监控库的完全重写版本。
现代化的、TypeScript 原生的跨平台系统监控库,提供全面的系统信息收集功能,具备智能缓存、事件驱动监控和强大的错误处理机制。
重大变更: 这是一个包含破坏性变更的主要版本发布,与 v1.x 不兼容。
bootTime / uptimeSeconds 字段,Linux 进程指标补充精确的 startTimegetSupportedPlatforms()、checkPlatformCapabilities() 等辅助工具。/bin/bash → /bin/sh、PowerShell 自动降级等回退策略。/proc,macOS 使用 sysctl/powermetrics,Windows 结合 PowerShell + WMI),并暴露自身支持的特性清单。| 功能 | Linux | macOS | Windows |
|---|---|---|---|
| CPU 使用率 / 信息 | ✅ | ✅ | ✅ |
| CPU 温度 | ⚠️ 依赖 /sys/class/thermal |
⚠️ 需 powermetrics(sudo) |
❌ |
| 内存压力 | ⚠️ 需额外工具 | ✅ | ⚠️ WMI 估算 |
| 磁盘 I/O 指标 | ✅ | ✅ | ❌ |
| 网络统计 | ✅(/proc/net/dev) |
✅(netstat -ib) |
⚠️ PowerShell 需管理员 |
| 进程详情 | ✅ | ✅ | ✅(WMI) |
| 系统服务 | ⚠️ 依赖 systemctl |
❌ | ✅ |
| 容器兼容 | ⚠️ 自动检测并降级 | ⚠️ 自动检测并降级 | ⚠️ 自动检测并降级 |
图例:✅ 完全支持 · ⚠️ 部分或受限 · ❌ 暂不支持
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils();
const report = await osutils.checkPlatformCapabilities();
console.table({
platform: report.platform,
supported: report.supported,
commands: report.capabilities.commands.join(','),
features: report.capabilities.features.join(',')
});
if (!report.supported) {
console.warn('❗ 当前平台部分能力不可用:', report.issues);
}
需要进一步排查时,还可以调用 AdapterFactory.getDebugInfo() 查看适配器特性与系统命令可用性。
在 容器环境 中库会自动:
- 通过 /.dockerenv、/proc/1/cgroup 或环境变量识别 Docker/Podman/Kubernetes;
- 检测到容器后禁用 systemctl 服务枚举,避免非 systemd 环境下报错;
- 当 ss 缺失时回退到 netstat,ip 缺失时回退到 ifconfig;
- 在返回的 MonitorError 中携带详细的主备命令错误,便于区分权限问题与真正的不支持;
- 通过 adapter.getSupportedFeatures() 保持特性标志同步,帮助监控器在功能不受支持时提前短路。
npm install node-os-utils
系统要求: - Node.js 18.0.0 或更高版本 - 支持的操作系统: Linux、macOS、Windows
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils();
// 获取 CPU 使用率
const cpuUsage = await osutils.cpu.usage();
if (cpuUsage.success) {
console.log('CPU 使用率:', cpuUsage.data + '%');
}
// 获取内存信息
const memInfo = await osutils.memory.info();
if (memInfo.success) {
console.log('内存:', memInfo.data);
}
// 获取系统概览
const overview = await osutils.overview();
console.log('系统概览:', overview);
const { OSUtils } = require('node-os-utils');
const osutils = new OSUtils();
osutils.cpu.usage().then(result => {
if (result.success) {
console.log('CPU 使用率:', result.data + '%');
}
});
// 替代实例化方法
const { createOSUtils } = require('node-os-utils');
const osutils = createOSUtils({
cacheEnabled: true,
cacheTTL: 10000
});
// 与 OSUtils 类相同的 API
const cpuUsage = await osutils.cpu.usage();
import { OSUtils } from 'node-os-utils';
const osutils = new OSUtils({
// 缓存设置
cacheEnabled: true,
cacheTTL: 5000,
maxCacheSize: 1000,
// 执行设置
timeout: 10000,
// 调试模式
debug: false,
// 监控器特定配置
cpu: {
cacheTTL: 30000,
// 是否将 iowait 从整体 CPU 使用率中排除(仅 Linux 生效)
// 默认 false:iowait 计入 overall,与传统监控工具行为一致
excludeIowait: false
},
memory: { cacheTTL: 5000 },
disk: { cacheTTL: 60000 }
});
// 配置单个监控器
const cpuMonitor = osutils.cpu
.withCaching(true, 30000)
.withConfig({ timeout: 5000 });
// 运行时配置缓存
osutils.configureCache({
enabled: true,
maxSize: 2000,
defaultTTL: 10000
});
所有操作都返回 MonitorResult<T> 对象,以保证一致的错误处理:
type MonitorResult<T> =
| {
success: true;
data: T;
timestamp: number;
cached: boolean;
platform: string;
}
| {
success: false;
error: MonitorError;
platform: string;
timestamp: number;
};
const result = await osutils.cpu.info();
if (result.success) {
// 成功:使用 result.data
console.log('CPU 型号:', result.data.model);
console.log('核心数:', result.data.cores);
} else {
// 错误:优雅处理
console.error('错误:', result.error?.message);
console.error('错误代码:', result.error?.code);
// 平台特定处理
if (result.error?.code === ErrorCode.PLATFORM_NOT_SUPPORTED) {
console.log('此功能在', result.platform, '上不可用');
}
}
enum ErrorCode {
PLATFORM_NOT_SUPPORTED = 'PLATFORM_NOT_SUPPORTED', // 当前平台不支持该功能
COMMAND_FAILED = 'COMMAND_FAILED', // 系统命令执行失败
PARSE_ERROR = 'PARSE_ERROR', // 命令输出或数据解析失败
PERMISSION_DENIED = 'PERMISSION_DENIED', // 权限不足无法完成操作
TIMEOUT = 'TIMEOUT', // 操作超过设定超时时间
INVALID_CONFIG = 'INVALID_CONFIG', // 提供的配置无效
NOT_AVAILABLE = 'NOT_AVAILABLE', // 指标暂时不可用
FILE_NOT_FOUND = 'FILE_NOT_FOUND', // 依赖的文件或路径不存在
NETWORK_ERROR = 'NETWORK_ERROR' // 网络操作失败
}
powermetrics 且需要管理员权限(sudo powermetrics -n 1 -i 1000 --samplers smc)。当命令不可用时,适配器会返回 PLATFORM_NOT_SUPPORTED。Get-NetAdapterStatistics、Get-CimInstance),遇到 PERMISSION_DENIED 或 COMMAND_FAILED 建议在提升权限的 PowerShell 会话中运行。/proc,若 ip、ss 等工具缺失,会自动回退到 ifconfig、netstat。你也可以提前通过 osutils.checkPlatformCapabilities() 验证依赖。MonitorResult.error.code,依据不同错误类型(超时、权限、平台不支持)给用户友好的提示。全面的 CPU 监控,具有实时功能。
// 基本 CPU 信息
const cpuInfo = await osutils.cpu.info();
if (cpuInfo.success) {
console.log('型号:', cpuInfo.data.model);
console.log('核心数:', cpuInfo.data.cores);
console.log('架构:', cpuInfo.data.architecture);
}
// CPU 使用率监控
const cpuUsage = await osutils.cpu.usage();
if (cpuUsage.success) {
console.log('CPU 使用率:', cpuUsage.data + '%');
}
// 详细使用率(包含每核数据)
const usageDetails = await osutils.cpu.usageDetailed();
if (usageDetails.success) {
console.log('整体使用率:', usageDetails.data.overall);
console.log('各核心使用率:', usageDetails.data.cores);
}
// 负载平均值(Linux/macOS)
const loadAvg = await osutils.cpu.loadAverage();
if (loadAvg.success) {
console.log('负载平均值:', loadAvg.data);
}
| 方法 | 返回类型 | 描述 | 平台支持 |
|---|---|---|---|
info() |
Promise<MonitorResult<CPUInfo>> |
CPU 型号、核心、线程、架构 | ✅ 全部 |
usage() |
Promise<MonitorResult<number>> |
CPU 使用率百分比 (0-100) | ✅ 全部 |
usageDetailed() |
Promise<MonitorResult<CPUUsage>> |
详细使用率(含每核心) | ✅ 全部 |
usageByCore() |
Promise<MonitorResult<number[]>> |
每核心使用率数组 | ✅ 全部 |
loadAverage() |
Promise<MonitorResult<LoadAverage>> |
负载平均值 (1, 5, 15 分钟) | ✅ Linux/macOS |
temperature() |
Promise<MonitorResult<Temperature[]>> |
CPU 温度传感器 | ⚠️ 有限 |
frequency() |
Promise<MonitorResult<FrequencyInfo[]>> |
当前 CPU 频率信息 | ⚠️ 有限 |
getCacheInfo() |
Promise<MonitorResult<any>> |
CPU 缓存层级信息 | ⚠️ 有限 |
coreCount() |
Promise<MonitorResult<{ physical: number; logical: number }>> |
物理/逻辑核心数量 | ✅ 全部 |
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
excludeIowait |
boolean |
false |
为 true 时,I/O 等待时间(iowait)将从 overall 使用率中剔除,适合 I/O 密集型场景下避免 CPU 使用率虚高。iowait 仍作为独立字段在 usageDetailed() 中返回。仅 Linux 生效。 |
// 在 I/O 密集型 Linux 环境中排除 iowait
const osutils = new OSUtils({
cpu: { excludeIowait: true }
});
const result = await osutils.cpu.usageDetailed();
if (result.success) {
console.log('整体使用率(不含 iowait):', result.data.overall + '%');
console.log('iowait:', result.data.iowait + '%'); // 仍可单独读取
}
// 每秒轮询一次使用率
const pollInterval = setInterval(async () => {
const result = await osutils.cpu.usage();
if (result.success) {
console.log(`CPU 使用率: ${result.data.toFixed(2)}%`);
if (result.data > 80) {
console.warn('⚠️ 检测到高 CPU 使用率!');
}
}
}, 1000);
setTimeout(() => {
clearInterval(pollInterval);
console.log('CPU 使用率轮询已停止');
}, 30000);
// 使用 monitor() 获取 CPU 基本信息快照
const cpuInfoSubscription = osutils.cpu.withCaching(false).monitor(5000, (info) => {
console.log('CPU 型号:', info.model);
});
setTimeout(() => cpuInfoSubscription.unsubscribe(), 20000);
带智能单位转换的详细内存信息。
// 带 DataSize 帮助方法的内存信息
const memInfo = await osutils.memory.info();
if (memInfo.success) {
console.log('总内存:', memInfo.data.total.toGB().toFixed(2) + ' GB');
console.log('可用:', memInfo.data.available.toGB().toFixed(2) + ' GB');
console.log('已用:', memInfo.data.used.toGB().toFixed(2) + ' GB');
console.log('使用率:', memInfo.data.usagePercentage.toFixed(2) + '%');
}
// 快速内存使用率百分比
const memUsage = await osutils.memory.usage();
if (memUsage.success) {
console.log('内存使用率:', memUsage.data.toFixed(2) + '%');
}
// 摘要视图
const memSummary = await osutils.memory.summary();
if (memSummary.success) {
console.log('摘要:', memSummary.data);
}
| 方法 | 返回类型 | 描述 | 平台支持 |
|---|---|---|---|
info() |
Promise<MonitorResult<MemoryInfo>> |
带 DataSize 对象的详细内存分解 | ✅ 全部 |
detailed() |
Promise<MonitorResult<MemoryInfo & { breakdown: Record<string, unknown> }>> |
含平台特定明细 | ⚠️ 平台 |
usage() |
Promise<MonitorResult<number>> |
内存使用率百分比 (0-100) | ✅ 全部 |
available() |
Promise<MonitorResult<DataSize>> |
可用内存量 | ✅ 全部 |
swap() |
Promise<MonitorResult<SwapInfo>> |
虚拟内存/交换信息 | ✅ 全部 |
pressure() |
Promise<MonitorResult<MemoryPressure>> |
内存压力指标 | ⚠️ 有限 |
summary() |
Promise<MonitorResult<{ total: string; used: string; available: string; usagePercentage: number; swap: { total: string; used: string; usagePercentage: number } }>> |
友好的汇总结果 | ✅ 全部 |
class DataSize {
constructor(bytes: number);
toBytes(): number;
toKB(): number;
toMB(): number;
toGB(): number;
toTB(): number;
toString(unit?: 'auto' | 'B' | 'KB' | 'MB' | 'GB' | 'TB'): string;
}
// 使用示例
const memory = await osutils.memory.info();
if (memory.success) {
console.log(memory.data.total.toString('GB')); // "16.00 GB"
console.log(memory.data.available.toString()); // 自动选择单位
}
全面的磁盘和存储监控。
// 所有磁盘信息
const diskInfo = await osutils.disk.info();
if (diskInfo.success) {
diskInfo.data.forEach(disk => {
console.log('文件系统:', disk.filesystem);
console.log('挂载点:', disk.mountpoint);
console.log('总容量:', disk.total.toString('GB'));
console.log('可用:', disk.available.toString('GB'));
console.log('使用率:', disk.usagePercentage + '%');
});
}
// 指定挂载点的使用情况
const rootUsage = await osutils.disk.usageByMountPoint('/');
if (rootUsage.success && rootUsage.data) {
console.log('根目录使用率:', rootUsage.data.usagePercentage + '%');
}
// I/O 统计
const ioStats = await osutils.disk.stats();
if (ioStats.success) {
ioStats.data.forEach(stat => {
console.log(`${stat.device}:`, {
readBytes: stat.readBytes.toString('MB'),
writeBytes: stat.writeBytes.toString('MB'),
readCount: stat.readCount,
writeCount: stat.writeCount
});
});
}
| 方法 | 返回类型 | 描述 | 平台支持 |
|---|---|---|---|
info() |
Promise<MonitorResult<DiskInfo[]>> |
磁盘 / 分区信息 | ✅ 全部 |
infoByDevice(device) |
Promise<MonitorResult<DiskInfo | null>> |
按设备或挂载点查询 | ✅ 全部 |
usage() |
Promise<MonitorResult<DiskUsage[]>> |
所有挂载点的使用情况 | ✅ 全部 |
usageByMountPoint(mountPoint) |
Promise<MonitorResult<DiskUsage | null>> |
指定挂载点使用情况 | ✅ 全部 |
overallUsage() |
Promise<MonitorResult<number>> |
所有磁盘加权平均使用率 | ✅ 全部 |
stats() |
Promise<MonitorResult<DiskStats[]>> |
I/O 统计摘要(需 includeStats) |
⚠️ 有限 |
mounts() |
Promise<MonitorResult<MountPoint[]>> |
挂载点配置详情 | ✅ 全部 |
filesystems() |
Promise<MonitorResult<FileSystem[]>> |
支持的文件系统类型 | ✅ 全部 |
spaceOverview() |
Promise<MonitorResult<{ total: DataSize; used: DataSize; available: DataSize; usagePercentage: number; disks: number }>> |
聚合空间使用情况 | ✅ 全部 |
healthCheck() |
Promise<MonitorResult<{ status: 'healthy' | 'warning' | 'critical'; issues: string[] }>> |
基础磁盘健康检查 | ⚠️ 有限 |
网络接口和流量监控。
```typescript // 网络接口 const interfaces = await osutils.network.interfaces(); if (interfaces.success) { interfaces.data.forEach(iface => { console.log('接口:', iface.name); console.log('地址:', iface.addresses); console.log('状态:', iface.state); }); }
// 网络总览 const overview = await osutils.network.overview(); if (overview.success) { console.log('总接收:', overview.data.totalRxBytes.toString('MB')); console.log('总发送:', overview.data.totalTxBytes.toString('MB')); }
// 接口统计信息
const stats = await osutils.network.statsAsync();
if (stats.success) {
stats.data.forEach(stat => {
console.log(${stat.interface}: RX ${stat.rxBytes.toString('MB')} | TX ${stat.txBytes.toString('MB')});
});
}
// 实时接口监控(返回接口快照) const netSub = osutils.network.monitor(5000, (snapshot) => { const active = snapshot.filter(iface => iface.state === 'up').ma
$ claude mcp add node-os-utils \
-- python -m otcore.mcp_server <graph>