MCPcopy Index your code
hub / github.com/SunilWang/node-os-utils

github.com/SunilWang/node-os-utils @v2.0.3

Chat with this repo
repository ↗ · DeepWiki ↗ · release v2.0.3 ↗ · + Follow
760 symbols 1,562 edges 51 files 486 documented · 64% 4 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

node-os-utils v2.0

[![NPM 版本][npm-image]][npm-url] [![NPM 下载量][downloads-image]][downloads-url] TypeScript 支持 Node.js 版本 许可证: MIT

🚀 版本 2.0 - 流行的 Node.js 操作系统监控库的完全重写版本。

现代化的、TypeScript 原生的跨平台系统监控库,提供全面的系统信息收集功能,具备智能缓存、事件驱动监控和强大的错误处理机制。

重大变更: 这是一个包含破坏性变更的主要版本发布,与 v1.x 不兼容。

✨ v2.0 新特性

🎯 核心改进

  • 🔧 TypeScript 优先: 使用严格类型的完全重写版本
  • 🏗️ 现代架构: 使用适配器模式的清洁、模块化设计
  • ⚡ 性能优化: 带 TTL 管理的智能缓存系统
  • 🛡️ 强大错误处理: 具有详细错误码的一致错误处理
  • 🔄 事件驱动: 具有订阅管理的实时监控
  • 📊 丰富数据类型: 具有单位转换的全面数据结构
  • 📆 时间线可追溯: 系统信息新增 bootTime / uptimeSeconds 字段,Linux 进程指标补充精确的 startTime

🌟 关键特性

  • 🌍 跨平台: Linux、macOS、Windows 支持,具有智能平台适配
  • 📝 零依赖: 仅使用内置模块的纯 Node.js 实现
  • ⚙️ 可配置: 缓存、超时和监控的灵活配置系统
  • 🎯 类型安全: 完整的 TypeScript 定义,支持 IntelliSense
  • 🔍 全面: CPU、内存、磁盘、网络、进程和系统监控
  • 📈 实时: 具有可自定义间隔的事件驱动监控
  • ✅ 状态更精准: 网络适配器保留原生接口状态,并在缺失时智能回退推断结果

🧱 架构速览

  • AdapterFactory 统一负责平台检测、适配器实例缓存,并提供 getSupportedPlatforms()checkPlatformCapabilities() 等辅助工具。
  • CommandExecutor 为不同系统提供统一的命令执行与错误封装,支持 /bin/bash/bin/sh、PowerShell 自动降级等回退策略。
  • 平台适配器 封装操作系统特定实现(Linux 依赖 /proc,macOS 使用 sysctl/powermetrics,Windows 结合 PowerShell + WMI),并暴露自身支持的特性清单。
  • CacheManager 提供基于 TTL 的智能缓存与 LRU 淘汰,显著降低高频监控时的系统开销。

🖥️ 平台支持矩阵

功能 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 缺失时回退到 netstatip 缺失时回退到 ifconfig; - 在返回的 MonitorError 中携带详细的主备命令错误,便于区分权限问题与真正的不支持; - 通过 adapter.getSupportedFeatures() 保持特性标志同步,帮助监控器在功能不受支持时提前短路。

🚀 安装

npm install node-os-utils

系统要求: - Node.js 18.0.0 或更高版本 - 支持的操作系统: Linux、macOS、Windows

🏁 快速开始

TypeScript

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);

JavaScript (CommonJS)

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'                  // 网络操作失败
}

🛠️ 故障排查与权限提示

  • macOS 温度指标 依赖 powermetrics 且需要管理员权限(sudo powermetrics -n 1 -i 1000 --samplers smc)。当命令不可用时,适配器会返回 PLATFORM_NOT_SUPPORTED
  • Windows 网络 / 进程指标 使用 PowerShell CIM 指令(Get-NetAdapterStatisticsGet-CimInstance),遇到 PERMISSION_DENIEDCOMMAND_FAILED 建议在提升权限的 PowerShell 会话中运行。
  • Linux 命令回退:大多数数据来自 /proc,若 ipss 等工具缺失,会自动回退到 ifconfignetstat。你也可以提前通过 osutils.checkPlatformCapabilities() 验证依赖。
  • 建议检查 MonitorResult.error.code,依据不同错误类型(超时、权限、平台不支持)给用户友好的提示。

📚 完整 API 参考

🔥 CPU 监控器

全面的 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);
}

CPU 方法

方法 返回类型 描述 平台支持
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 }>> 物理/逻辑核心数量 ✅ 全部

CPU 配置项

配置项 类型 默认值 说明
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 + '%'); // 仍可单独读取
}

实时 CPU 监控

// 每秒轮询一次使用率
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 } }>> 友好的汇总结果 ✅ 全部

DataSize 对象

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

Extension points exported contracts — how you extend this code

MonitorSubscription (Interface)
(no doc) [2 implementers]
src/types/common.ts
CacheItem (Interface)
* 缓存项接口
src/core/cache-manager.ts
ProcessStubOptions (Interface)
(no doc)
test/unit/monitors/process-monitor.test.ts
CpuTimes (Interface)
(no doc)
src/adapters/linux-adapter.ts
PlatformAdapter (Interface)
(no doc) [2 implementers]
src/types/platform.ts
CacheStats (Interface)
(no doc)
src/core/cache-manager.ts
CpuStatSnapshot (Interface)
(no doc)
src/adapters/linux-adapter.ts
CommandResult (Interface)
(no doc)
src/types/platform.ts

Core symbols most depended-on inside this repo

now
called by 68
src/types/common.ts
safeParseNumber
called by 66
src/monitors/cpu-monitor.ts
asyncTest
called by 55
test/utils/test-base.ts
executeCommand
called by 37
src/adapters/macos-adapter.ts
toBytes
called by 32
src/types/common.ts
safeParseNumber
called by 27
src/monitors/memory-monitor.ts
toString
called by 26
src/types/common.ts
safeParseNumber
called by 20
src/monitors/disk-monitor.ts

Shape

Method 598
Class 62
Function 59
Interface 40
Enum 1

Languages

TypeScript100%

Modules by API surface

src/adapters/linux-adapter.ts72 symbols
src/adapters/macos-adapter.ts60 symbols
test/unit/core/platform-adapter.test.ts42 symbols
src/adapters/windows-adapter.ts41 symbols
src/types/platform.ts39 symbols
test/utils/test-base.ts37 symbols
test/unit/monitors/process-monitor.test.ts36 symbols
src/core/base-monitor.ts35 symbols
src/monitors/network-monitor.ts34 symbols
src/monitors/process-monitor.ts33 symbols
src/monitors/cpu-monitor.ts32 symbols
src/monitors/system-monitor.ts31 symbols

For agents

$ claude mcp add node-os-utils \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact