-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
79 lines (66 loc) · 1.91 KB
/
app.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const express = require("express");
const cors = require("cors");
const path = require("path");
const os = require("os");
const app = express();
const PORT = process.env.PORT || 3002;
let isIntervalRunning = false;
let avg = 0;
const smoothingFactor = 2;
// Middleware setup
app.use(cors());
app.use(express.static(path.join(__dirname, "client/build")));
// Start the server
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// Function to calculate CPU average
function calculateCpuAverage() {
const cpus = os.cpus();
let totalIdle = 0;
let totalTick = 0;
cpus.forEach(cpu => {
for (const timeType in cpu.times) {
totalTick += cpu.times[timeType];
}
totalIdle += cpu.times.idle;
});
return {
idle: totalIdle / cpus.length,
total: totalTick / cpus.length,
};
}
// Initialize CPU average
let previousCpuTimes = calculateCpuAverage();
// Function to start the CPU usage interval
function monitorCpuUsage() {
setInterval(() => {
const currentCpuTimes = calculateCpuAverage();
const idleDifference = currentCpuTimes.idle - previousCpuTimes.idle;
const totalDifference = currentCpuTimes.total - previousCpuTimes.total;
const currentCpuUsage = 100 - Math.floor((100 * idleDifference) / totalDifference);
// Smooth out the average using exponential moving average
avg = parseFloat(
(avg + (currentCpuUsage - avg) / smoothingFactor).toFixed(2)
);
console.log(`CPU Usage: ${avg}%`);
previousCpuTimes = currentCpuTimes;
}, 1000);
}
// API endpoint to get the current CPU usage average
app.get("/api", (req, res) => {
if (!isIntervalRunning) {
monitorCpuUsage();
isIntervalRunning = true;
}
res.json({
message: "ok",
data: {
avg,
},
});
});
// Catch-all route to serve the client application
// app.get("*", (req, res) => {
// res.sendFile(path.join(__dirname, "client/build", "index.html"));
// });