Node.js种os模块详解

Node.js 中 os 模块全部 API 详解

1. 系统信息

javascript 复制代码
const os = require('os');

// 1. 操作系统平台
console.log('操作系统平台:', os.platform());  // 'darwin', 'win32', 'linux' 等

// 2. 操作系统类型
console.log('操作系统类型:', os.type());  // 'Darwin', 'Windows_NT', 'Linux' 等

// 3. 操作系统版本
console.log('操作系统版本:', os.release());  // '18.7.0', '10.0.19041' 等

// 4. 操作系统架构
console.log('操作系统架构:', os.arch());  // 'x64', 'arm64' 等

// 5. 主机名
console.log('主机名:', os.hostname());

// 6. 系统运行时间
console.log('系统运行时间(秒):', os.uptime());

// 7. 系统负载
console.log('系统负载:', os.loadavg());  // [1.5, 1.2, 1.0] 1分钟、5分钟、15分钟的平均负载

// 8. 系统常量
console.log('系统常量:', {
  EOL: os.EOL,  // 行尾符号
  constants: os.constants  // 系统常量
});

2. CPU 信息

javascript 复制代码
const os = require('os');

// 1. CPU 架构
console.log('CPU 架构:', os.arch());

// 2. CPU 核心数
console.log('CPU 核心数:', os.cpus().length);

// 3. CPU 详细信息
const cpus = os.cpus();
cpus.forEach((cpu, index) => {
  console.log(`CPU ${index}:`, {
    model: cpu.model,      // CPU 型号
    speed: cpu.speed,      // CPU 速度(MHz)
    times: {               // CPU 时间
      user: cpu.times.user,       // 用户代码使用时间
      nice: cpu.times.nice,       // 优先级进程使用时间
      sys: cpu.times.sys,         // 系统代码使用时间
      idle: cpu.times.idle,       // 空闲时间
      irq: cpu.times.irq          // 中断请求时间
    }
  });
});

// 4. CPU 使用率计算
function getCPUUsage() {
  const cpus = os.cpus();
  const total = cpus.reduce((acc, cpu) => {
    const total = Object.values(cpu.times).reduce((a, b) => a + b);
    return acc + total;
  }, 0);
  
  const idle = cpus.reduce((acc, cpu) => acc + cpu.times.idle, 0);
  
  return ((total - idle) / total) * 100;
}

console.log('CPU 使用率:', getCPUUsage(), '%');

3. 内存信息

javascript 复制代码
const os = require('os');

// 1. 总内存
console.log('总内存:', os.totalmem(), 'bytes');
console.log('总内存:', os.totalmem() / 1024 / 1024, 'MB');
console.log('总内存:', os.totalmem() / 1024 / 1024 / 1024, 'GB');

// 2. 空闲内存
console.log('空闲内存:', os.freemem(), 'bytes');
console.log('空闲内存:', os.freemem() / 1024 / 1024, 'MB');
console.log('空闲内存:', os.freemem() / 1024 / 1024 / 1024, 'GB');

// 3. 内存使用率
function getMemoryUsage() {
  const total = os.totalmem();
  const free = os.freemem();
  return ((total - free) / total) * 100;
}

console.log('内存使用率:', getMemoryUsage(), '%');

// 4. 内存详细信息
function getMemoryInfo() {
  const total = os.totalmem();
  const free = os.freemem();
  const used = total - free;
  
  return {
    total: {
      bytes: total,
      mb: total / 1024 / 1024,
      gb: total / 1024 / 1024 / 1024
    },
    free: {
      bytes: free,
      mb: free / 1024 / 1024,
      gb: free / 1024 / 1024 / 1024
    },
    used: {
      bytes: used,
      mb: used / 1024 / 1024,
      gb: used / 1024 / 1024 / 1024
    },
    usage: (used / total) * 100
  };
}

console.log('内存详细信息:', getMemoryInfo());

4. 网络接口

javascript 复制代码
const os = require('os');

// 1. 网络接口信息
const interfaces = os.networkInterfaces();
console.log('网络接口:', interfaces);

// 2. 获取本地 IP 地址
function getLocalIP() {
  const interfaces = os.networkInterfaces();
  for (const name of Object.keys(interfaces)) {
    for (const interface of interfaces[name]) {
      // 跳过内部接口和非 IPv4 地址
      if (interface.internal || interface.family !== 'IPv4') {
        continue;
      }
      return interface.address;
    }
  }
  return '127.0.0.1';
}

console.log('本地 IP 地址:', getLocalIP());

// 3. 获取所有网络接口信息
function getNetworkInfo() {
  const interfaces = os.networkInterfaces();
  const info = {};
  
  for (const name of Object.keys(interfaces)) {
    info[name] = interfaces[name].map(interface => ({
      address: interface.address,
      family: interface.family,
      internal: interface.internal,
      netmask: interface.netmask,
      mac: interface.mac
    }));
  }
  
  return info;
}

console.log('网络接口详细信息:', getNetworkInfo());

5. 用户信息

javascript 复制代码
const os = require('os');

// 1. 当前用户信息
console.log('当前用户:', os.userInfo());

// 2. 主目录
console.log('主目录:', os.homedir());

// 3. 临时目录
console.log('临时目录:', os.tmpdir());

// 4. 用户详细信息
function getUserInfo() {
  const user = os.userInfo();
  return {
    username: user.username,
    uid: user.uid,
    gid: user.gid,
    homedir: user.homedir,
    shell: user.shell
  };
}

console.log('用户详细信息:', getUserInfo());

6. 系统常量

javascript 复制代码
const os = require('os');

// 1. 信号常量
console.log('信号常量:', os.constants.signals);

// 2. 错误码常量
console.log('错误码常量:', os.constants.errno);

// 3. 优先级常量
console.log('优先级常量:', os.constants.priority);

// 4. 文件系统常量
console.log('文件系统常量:', os.constants.fs);

// 5. 网络常量
console.log('网络常量:', os.constants.net);

7. 实用工具函数

javascript 复制代码
const os = require('os');

// 1. 系统信息摘要
function getSystemInfo() {
  return {
    platform: os.platform(),
    type: os.type(),
    release: os.release(),
    arch: os.arch(),
    hostname: os.hostname(),
    uptime: os.uptime(),
    loadavg: os.loadavg(),
    totalmem: os.totalmem(),
    freemem: os.freemem(),
    cpus: os.cpus().length,
    networkInterfaces: os.networkInterfaces(),
    userInfo: os.userInfo(),
    homedir: os.homedir(),
    tmpdir: os.tmpdir()
  };
}

// 2. 性能监控
function monitorPerformance(interval = 1000) {
  let lastCPUUsage = getCPUUsage();
  let lastCheck = Date.now();
  
  setInterval(() => {
    const now = Date.now();
    const cpuUsage = getCPUUsage();
    const memoryUsage = getMemoryUsage();
    
    console.log('性能监控:', {
      timestamp: new Date().toISOString(),
      cpu: {
        usage: cpuUsage,
        change: cpuUsage - lastCPUUsage
      },
      memory: {
        usage: memoryUsage,
        free: os.freemem() / 1024 / 1024,
        total: os.totalmem() / 1024 / 1024
      },
      load: os.loadavg(),
      uptime: os.uptime()
    });
    
    lastCPUUsage = cpuUsage;
    lastCheck = now;
  }, interval);
}

// 3. 网络诊断
function networkDiagnostics() {
  const interfaces = os.networkInterfaces();
  const diagnostics = {};
  
  for (const name of Object.keys(interfaces)) {
    diagnostics[name] = interfaces[name].map(interface => ({
      address: interface.address,
      family: interface.family,
      internal: interface.internal,
      netmask: interface.netmask,
      mac: interface.mac,
      status: interface.internal ? 'internal' : 'external'
    }));
  }
  
  return diagnostics;
}

// 4. 系统健康检查
function healthCheck() {
  const cpuUsage = getCPUUsage();
  const memoryUsage = getMemoryUsage();
  const load = os.loadavg();
  
  return {
    status: 'healthy',
    checks: {
      cpu: {
        usage: cpuUsage,
        status: cpuUsage < 80 ? 'ok' : 'warning'
      },
      memory: {
        usage: memoryUsage,
        status: memoryUsage < 90 ? 'ok' : 'warning'
      },
      load: {
        '1m': load[0],
        '5m': load[1],
        '15m': load[2],
        status: load[0] < os.cpus().length ? 'ok' : 'warning'
      }
    },
    timestamp: new Date().toISOString()
  };
}

8. 实际应用示例

javascript 复制代码
const os = require('os');

// 1. 系统监控服务
class SystemMonitor {
  constructor(interval = 5000) {
    this.interval = interval;
    this.history = [];
    this.maxHistory = 100;
  }
  
  start() {
    this.timer = setInterval(() => {
      const stats = this.collectStats();
      this.history.push(stats);
      
      if (this.history.length > this.maxHistory) {
        this.history.shift();
      }
      
      this.checkAlerts(stats);
    }, this.interval);
  }
  
  stop() {
    clearInterval(this.timer);
  }
  
  collectStats() {
    return {
      timestamp: new Date().toISOString(),
      cpu: {
        usage: getCPUUsage(),
        cores: os.cpus().length,
        load: os.loadavg()
      },
      memory: {
        total: os.totalmem(),
        free: os.freemem(),
        usage: getMemoryUsage()
      },
      network: networkDiagnostics(),
      uptime: os.uptime()
    };
  }
  
  checkAlerts(stats) {
    if (stats.cpu.usage > 80) {
      console.warn('CPU 使用率过高:', stats.cpu.usage, '%');
    }
    
    if (stats.memory.usage > 90) {
      console.warn('内存使用率过高:', stats.memory.usage, '%');
    }
    
    if (stats.cpu.load[0] > os.cpus().length) {
      console.warn('系统负载过高:', stats.cpu.load[0]);
    }
  }
  
  getHistory() {
    return this.history;
  }
  
  getCurrentStats() {
    return this.collectStats();
  }
}

// 2. 系统信息 API
const express = require('express');
const app = express();

app.get('/api/system', (req, res) => {
  res.json(getSystemInfo());
});

app.get('/api/performance', (req, res) => {
  res.json({
    cpu: {
      usage: getCPUUsage(),
      cores: os.cpus().length,
      load: os.loadavg()
    },
    memory: {
      total: os.totalmem(),
      free: os.freemem(),
      usage: getMemoryUsage()
    }
  });
});

app.get('/api/network', (req, res) => {
  res.json(networkDiagnostics());
});

app.get('/api/health', (req, res) => {
  res.json(healthCheck());
});

// 3. 系统资源限制
function checkResourceLimits() {
  const limits = {
    cpu: {
      cores: os.cpus().length,
      load: os.loadavg()[0],
      threshold: os.cpus().length * 0.8
    },
    memory: {
      total: os.totalmem(),
      free: os.freemem(),
      threshold: os.totalmem() * 0.9
    }
  };
  
  return {
    limits,
    warnings: {
      cpu: limits.cpu.load > limits.cpu.threshold,
      memory: limits.memory.free < (limits.memory.total - limits.memory.threshold)
    }
  };
}

os 模块的主要特点:

  1. 提供系统信息和资源使用情况
  2. 支持 CPU、内存、网络等硬件信息获取
  3. 提供用户和系统常量信息
  4. 支持性能监控和诊断
  5. 跨平台兼容性好

使用建议:

  1. 合理使用系统资源监控
  2. 注意内存使用和 CPU 负载
  3. 实现适当的告警机制
  4. 考虑跨平台兼容性
  5. 定期清理临时文件
相关推荐
哎哟喂_!17 小时前
深入理解 Node.js 模块化(CommonJS):原理、用法与避坑指南
node.js
阿里小阿希18 小时前
解决 pnpm dev 运行报错的坎坷历程
前端·node.js
Q_Q196328847520 小时前
python小区物业管理系统-小区物业报修系统
开发语言·spring boot·python·django·flask·node.js·php
老兵发新帖21 小时前
NestJS 框架深度解析
后端·node.js
Q_Q19632884752 天前
python小说网站管理系统-小说阅读系统
开发语言·spring boot·python·django·flask·node.js·php
m0_zj2 天前
57.[前端开发-前端工程化]Day04-webpack插件模式-搭建本地服务器
前端·webpack·node.js
盛夏绽放2 天前
Vue3 + Node.js 实现客服实时聊天系统(WebSocket + Socket.IO 详解)
websocket·网络协议·node.js
layman05282 天前
node.js 实战——express图片保存到本地或服务器(七牛云、腾讯云、阿里云)
node.js·express
m0_zj2 天前
58.[前端开发-前端工程化]Day05-webpack-Git安装-配置-Git命令
前端·webpack·node.js
Attacking-Coder2 天前
前端面试宝典---JavaScript import 与 Node.js require 的区别
前端·javascript·node.js