-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (47 loc) · 1.68 KB
/
server.js
File metadata and controls
55 lines (47 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const express = require('express')
const os = require('os')
const app = express()
const PORT = 3001
function getCpuUsage() {
try {
const { execSync } = require('child_process')
const output = execSync('mpstat -P ALL 1 1 | grep "all" | grep -v "Average"', { encoding: 'utf8' })
const parts = output.trim().split(/\s+/)
const idle = parseFloat(parts[parts.length - 1])
return Math.round(100 - idle)
} catch (e) {
return 0
}
}
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
next()
})
app.get('/api/server-status', (req, res) => {
const cpuUsage = getCpuUsage()
const memTotal = os.totalmem() / 1024 / 1024 / 1024
const memUsed = (os.totalmem() - os.freemem()) / 1024 / 1024 / 1024
const memUsage = Math.round((memUsed / memTotal) * 100)
const { execSync } = require('child_process')
let diskUsage = 0, diskTotal = 0, diskUsed = 0
try {
const dfOutput = execSync('df -h /', { encoding: 'utf8' }).split('\n')[1].split(/\s+/)
diskTotal = parseFloat(dfOutput[1].replace('%', ''))
diskUsed = parseFloat(dfOutput[2].replace('%', ''))
diskUsage = parseFloat(dfOutput[4].replace('%', ''))
} catch (e) {}
const uptimeSeconds = os.uptime()
const days = Math.floor(uptimeSeconds / 86400)
const hours = Math.floor((uptimeSeconds % 86400) / 3600)
const minutes = Math.floor((uptimeSeconds % 3600) / 60)
const uptime = `${days}天${hours}时${minutes}分`
res.json({
cpuUsage,
memUsage,
diskUsage,
uptime
})
})
app.listen(PORT, () => {
console.log(`服务器状态API运行在 http://localhost:${PORT}`)
})