Node.js OS 模块 — 系统信息
获取 CPU、内存、网络接口等操作系统信息 · 难度:入门 · +15XP
os 模块
os 模块提供操作系统层面的信息。服务器监控、性能分析、系统检测都会用到。
常用方法
| 方法 | 返回 |
|---|---|
os.cpus() | CPU 核心信息数组 |
os.totalmem() / freemem() | 总内存 / 可用内存(字节) |
os.hostname() | 主机名 |
os.platform() | 操作系统平台(win32/darwin/linux) |
os.uptime() | 系统运行时间(秒) |
os.networkInterfaces() | 网络接口详情 |
os.homedir() | 用户主目录 |
实际应用:简易系统监控
const os = require("os");
function getSystemInfo() {
return {
主机名: os.hostname(),
系统: os.platform(),
已运行: Math.floor(os.uptime() / 3600) + " 小时",
CPU核心: os.cpus().length + " 核",
内存: (os.totalmem() / 1024 / 1024 / 1024).toFixed(1) + " GB",
可用内存: (os.freemem() / 1024 / 1024 / 1024).toFixed(1) + " GB"
};
}