-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
68 lines (57 loc) · 1.47 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
const express = require("express");
const app = express();
const cors = require('cors');
const path = require("path");
const PORT = process.env.PORT || 3002;
app.listen(PORT, function () {
console.log(`listening on port ${PORT}`);
});
app.use(cors());
let intervalStarted = false;
const os = require("os");
let avg = 0;
let n = 2;
function cpuAverage() {
let totalIdle = 0,
totalTick = 0;
let cpus = os.cpus();
for (let i = 0, len = cpus.length; i < len; i++) {
let cpu = cpus[i];
for (type in cpu.times) {
totalTick += cpu.times[type];
}
totalIdle += cpu.times.idle;
}
return {
idle: totalIdle / cpus.length,
total: totalTick / cpus.length
};
}
let startTimes = cpuAverage();
function startInterval() {
setInterval(function () {
let endTimes = cpuAverage();
let idleDelta = endTimes.idle - startTimes.idle;
let totalDelta = endTimes.total - startTimes.total;
let percentageCPU = 100 - ~~(100 * idleDelta / totalDelta);
avg = parseFloat((avg + (percentageCPU - avg) / n).toFixed(2));
console.log(avg + "% CPU Usage.");
startTimes = endTimes;
}, 1000);
}
app.get("/api", function (req, res) {
if (!intervalStarted) {
startInterval();
intervalStarted = true;
}
res.json({
message: "ok",
data: {
avg
},
});
});
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", function (req, res) {
res.sendFile(path.join(__dirname, "client/build", "index.html"));
});