-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (65 loc) · 1.92 KB
/
index.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
const os = require("os");
const si = require("systeminformation");
const checkDiskSpace = require("check-disk-space");
const currentPath = process.cwd();
const cpuAverage = () => {
var totalIdle = 0, totalTick = 0;
var cpus = os.cpus();
for (var i = 0, len = cpus.length; i < len; i++) {
var 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 };
}
const arrAvg = (arr) => {
if (arr && arr.length >= 1) {
const sumArr = arr.reduce((a, b) => a + b, 0)
return sumArr / arr.length;
}
};
const getCPULoadAVG = (avgTime = 1000, delay = 100) => {
return new Promise((resolve, reject) => {
const n = ~~(avgTime / delay);
if (n <= 1) {
reject("Error: interval too small");
}
let i = 0;
let samples = [];
const avg1 = cpuAverage();
let interval = setInterval(() => {
if (i >= n) {
clearInterval(interval);
resolve(~~((arrAvg(samples) * 100)));
}
const avg2 = cpuAverage();
const totalDiff = avg2.total - avg1.total;
const idleDiff = avg2.idle - avg1.idle;
samples[i] = (1 - idleDiff / totalDiff);
i++;
}, delay);
});
}
exports.cpu = (callback) => {
getCPULoadAVG(1000, 100).then((avg) => {
callback(avg / 100);
});
}
exports.mem = (callback) => {
si.mem((mem) => {
let memoryUsage = mem.active / mem.total;
callback(
Math.round(memoryUsage * 100) / 100
);
});
}
exports.disk = (callback) => {
checkDiskSpace(currentPath).then((diskSpace) => {
let used = diskSpace.size - diskSpace.free;
callback(
Math.round(used / diskSpace.size * 100) / 100
);
})
}