const os = require('os'); const http = require('http'); // 获取系统信息 const getSystemInfo = () => { try { const totalMem = (os.totalmem() / (1024 ** 3)).toFixed(2) + ' GB'; const freeMem = (os.freemem() / (1024 ** 3)).toFixed(2) + ' GB'; const usedMem = ((os.totalmem() - os.freemem()) / (1024 ** 3)).toFixed(2) + ' GB'; const memUsage = (((os.totalmem() - os.freemem()) / os.totalmem()) * 100).toFixed(2) + '%'; const cpus = os.cpus(); const cpuModel = cpus[0]?.model || 'Unknown'; const cpuCores = cpus.length; return { hostname: os.hostname(), platform: os.platform(), arch: os.arch(), uptime: (os.uptime() / 3600).toFixed(2) + ' hours', // 内存信息:使用前面计算好的变量 totalMem, // 总内存大小 usedMem, // 已使用内存 freeMem, // 空闲内存 memUsage, // 内存使用率 // CPU信息:使用前面计算好的变量 cpuModel, // CPU型号 cpuCores // CPU核心数 }; } catch (error) { console.error('获取系统信息失败:', error.message); return {}; } }; // 创建HTTP服务器 const server = http.createServer((req, res) => { if (req.url === '/') { const systemInfo = getSystemInfo(); const html = ` 系统信息监控

🖥️ 系统信息监控

主机名: ${systemInfo.hostname || 'N/A'}
平台: ${systemInfo.platform || 'N/A'}
架构: ${systemInfo.arch || 'N/A'}
运行时间: ${systemInfo.uptime || 'N/A'}
总内存: ${systemInfo.totalMem || 'N/A'}
已用内存: ${systemInfo.usedMem || 'N/A'}
空闲内存: ${systemInfo.freeMem || 'N/A'}
内存使用率: ${systemInfo.memUsage || 'N/A'}
CPU型号: ${systemInfo.cpuModel || 'N/A'}
CPU核心数: ${systemInfo.cpuCores || 'N/A'}
`; res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(html); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('页面未找到'); } }); // 启动服务器 const PORT = 3000; server.listen(PORT, () => { console.log(`🚀 服务器运行在 http://localhost:${PORT}`); });