87 lines
3.1 KiB
JavaScript
87 lines
3.1 KiB
JavaScript
const express = require('express');
|
||
const router = express.Router();
|
||
const si = require('systeminformation');
|
||
const os = require('os');
|
||
const fs = require('fs').promises;
|
||
|
||
// 获取系统信息的API
|
||
router.get('/system-info', async (req, res) => {
|
||
try {
|
||
// 获取基本系统信息
|
||
const [osInfo, cpuInfo, memInfo, diskInfo, networkStats] = await Promise.all([
|
||
si.osInfo(),
|
||
si.cpu(),
|
||
si.mem(),
|
||
si.fsSize(),
|
||
si.networkStats()
|
||
]);
|
||
|
||
// 获取各个CPU核心的使用率
|
||
const cpuCoreUsage = await si.currentLoad();
|
||
|
||
// 检测隔离的CPU核心
|
||
let isolatedCores = [];
|
||
try {
|
||
// 在Linux系统上,通过读取/sys/devices/system/cpu/isolated文件获取隔离的CPU核心
|
||
if (os.platform() === 'linux') {
|
||
const isolatedContent = await fs.readFile('/sys/devices/system/cpu/isolated', 'utf8');
|
||
if (isolatedContent && isolatedContent.trim() !== '') {
|
||
// 处理如"0-2,4,6-8"这样的格式
|
||
const ranges = isolatedContent.trim().split(',');
|
||
for (const range of ranges) {
|
||
if (range.includes('-')) {
|
||
const [start, end] = range.split('-').map(Number);
|
||
for (let i = start; i <= end; i++) {
|
||
isolatedCores.push(i);
|
||
}
|
||
} else {
|
||
isolatedCores.push(Number(range));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.warn('无法读取隔离CPU信息:', error);
|
||
}
|
||
|
||
// 计算内存使用率(使用第一种方式,与资源管理器一致)
|
||
const memoryUsedPercent = Math.round((memInfo.total - memInfo.available) / memInfo.total * 100);
|
||
|
||
// 计算网络带宽 (Mbps)
|
||
const downloadBandwidth = (networkStats[0].rx_sec / 1024 / 1024) * 8; // 下载带宽 Mbps
|
||
const uploadBandwidth = (networkStats[0].tx_sec / 1024 / 1024) * 8; // 上传带宽 Mbps
|
||
|
||
// 构造响应数据
|
||
const systemInfo = {
|
||
os: `${osInfo.distro} ${osInfo.release} ${osInfo.arch}`,
|
||
kernel: `${osInfo.kernel}`, // 添加内核版本
|
||
cpuCores: cpuInfo.cores,
|
||
ipAddress: Object.values(os.networkInterfaces())
|
||
.flat()
|
||
.filter(item => !item.internal && item.family === 'IPv4')
|
||
.map(item => item.address)[0] || 'Unknown',
|
||
isolatedCores: isolatedCores,
|
||
|
||
// 指标数据
|
||
metrics: {
|
||
'内存使用率': memoryUsedPercent,
|
||
'磁盘使用率': Math.round(diskInfo[0].used / diskInfo[0].size * 100),
|
||
'网络带宽': 0, // 占位符,前端不会使用这个值
|
||
'下载带宽': Math.round(downloadBandwidth * 10) / 10, // 保留一位小数的Mbps值
|
||
'上传带宽': Math.round(uploadBandwidth * 10) / 10 // 保留一位小数的Mbps值
|
||
}
|
||
};
|
||
|
||
// 添加每个CPU核心的使用率
|
||
for (let i = 0; i < cpuInfo.cores; i++) {
|
||
systemInfo.metrics[`CPU${i}使用率`] = Math.round(cpuCoreUsage.cpus[i].load);
|
||
}
|
||
|
||
res.json(systemInfo);
|
||
} catch (error) {
|
||
console.error('获取系统信息失败:', error);
|
||
res.status(500).json({ error: '获取系统信息失败', message: error.message });
|
||
}
|
||
});
|
||
|
||
module.exports = router;
|