feat: 添加后台主页实现
This commit is contained in:
1 parent
c7b5ef75a3
commit
5e254af81f
3 files changed
+328
-5
No files matched your search
@@ -0,0 +1,70 @@
|
||||
import os from 'os';
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
// 获取CPU信息
|
||||
const cpuUsage = getCpuUsage();
|
||||
|
||||
// 获取内存信息
|
||||
const totalMemory = os.totalmem();
|
||||
const freeMemory = os.freemem();
|
||||
const memoryUsage = {
|
||||
total: formatBytes(totalMemory),
|
||||
free: formatBytes(freeMemory),
|
||||
used: formatBytes(totalMemory - freeMemory),
|
||||
percent: Math.round(((totalMemory - freeMemory) / totalMemory) * 100)
|
||||
};
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
cpu: {
|
||||
usage: cpuUsage
|
||||
},
|
||||
memory: memoryUsage
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error fetching performance info:', error);
|
||||
return {
|
||||
success: false,
|
||||
message: '获取性能数据失败'
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// 格式化字节数为可读格式
|
||||
function formatBytes(bytes: number) {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
|
||||
const k = 1024;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
// 获取CPU使用率
|
||||
function getCpuUsage() {
|
||||
try {
|
||||
const cpus = os.cpus();
|
||||
let totalIdle = 0;
|
||||
let totalTick = 0;
|
||||
|
||||
cpus.forEach(cpu => {
|
||||
for (const type in cpu.times) {
|
||||
totalTick += cpu.times[type as keyof typeof cpu.times];
|
||||
}
|
||||
totalIdle += cpu.times.idle;
|
||||
});
|
||||
|
||||
const idle = totalIdle / cpus.length;
|
||||
const total = totalTick / cpus.length;
|
||||
const usagePercent = Math.round(100 - (idle / total * 100));
|
||||
|
||||
return usagePercent;
|
||||
} catch (error) {
|
||||
console.error('Error calculating CPU usage:', error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user