-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
161 lines (136 loc) · 4.67 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
/**
* windows-cpu module for Node.js to get various load statistics.
* @module windows-cpu
* @author Kyle Ross
* @license MIT License
*/
"use strict";
const fs = require('fs');
const path = require('path');
const util = require('util');
const cp = require('child_process');
const platform = require('os').platform();
const exec = util.promisify(cp.exec);
const execFile = util.promisify(cp.execFile);
/**
* @class Public class for WindowsCPU
*/
class WindowsCPU {
constructor() {
/**
* Access to uninstantiated WindowsCPU class
* @type {Class}
*/
this.WindowsCPU = WindowsCPU;
/**
* Path the `wmic` executable
* @type {String}
*/
this.wmic = path.join(process.env.SystemRoot || '/', 'System32', 'wbem', 'wmic.exe');
}
/**
* Checks if the current platform is supported by windows-cpu
* @return {Boolean} Returns `true` if platform is supported, otherwise `false`.
*/
isSupported() {
if(platform !== 'win32') return false;
try {
fs.accessSync(this.wmic);
} catch(e) {
return false;
}
return true;
}
/**
* Gets the total load in percent for all processes running on the current machine per CPU.
* @async
* @return {Promise<Array>}
*/
async totalLoad() {
let { stdout, stderr } = await execFile(this.wmic, ['cpu', 'get', 'loadpercentage']).catch(e => { throw e; });
if(stderr) throw new Error(stderr);
return (stdout.match(/\d+/g) || []).map(x => +(x.trim()));
}
/**
* Finds the current processor load for all processes or a specific process name or id.
* @async
* @param {?String} arg Optional process name or id to lookup
* @return {Promise<Object>}
*/
async findLoad(arg) {
let cmd = `${this.wmic} path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime,IDProcess`;
if(arg) cmd += ` | findstr /i /c:${this._shellEscape(arg)}`;
let { stdout, stderr } = await exec(cmd).catch(e => { throw e; });
if(stderr) throw new Error(stderr);
if(!stdout) return { load: 0, results: [] };
let found = stdout.replace(/[^\S\n]+/g, ':').replace(/:\s/g, '|').split('|')
.filter(v => !!v)
.map(v => {
let [pid, proc, load] = v.split(':');
return {
pid: +pid,
process: proc,
load: +load
};
});
let load = found.reduce((acc, val) => acc + val.load, 0);
return { load, found };
}
/**
* Retrieves the current cpu load for all node processes running on the current machine
* @async
* @return {Promise<Object>}
*/
nodeLoad() {
return this.findLoad('node');
}
/**
* Retrieves the current cpu load for this process.
* @async
* @return {Promise<Object>}
*/
thisLoad() {
return this.findLoad(process.pid);
}
/**
* Gets list of all processors in the current machine.
* @async
* @return {Promise<Array>}
*/
async cpuInfo() {
let { stdout, stderr } = await execFile(this.wmic, ['cpu', 'get', 'Name']).catch(e => { throw e; });
if(stderr) throw new Error(stderr);
let cpus = stdout.match(/[^\r\n]+/g).map(v => v.trim());
cpus.shift();
return cpus;
}
/**
* Gets the total memory usage on the machine in KB, MB and GB.
* @return {Promise<Object>}
*/
async totalMemoryUsage() {
let results = { usageInKb: 0, usageInMb: 0, usageInGb: 0 };
let { stdout, stderr } = await exec('tasklist /FO csv /nh').catch(e => { throw e; });
if(stderr) throw new Error(stderr);
results.usageInKb = stdout.match(/[^\r\n]+/g)
.map(v => {
let amt = +v.split('","')[4].replace(/[^\d]/g, '');
return (!isNaN(amt) && typeof amt === 'number') ? amt : 0;
})
.reduce((prev, current) => prev + current);
results.usageInMb = results.usageInKb / 1024;
results.usageInGb = results.usageInMb / 1024;
return results;
}
/**
* Sanitizes input to prevent malicious shell injection
* @private
* @param {String} arg The string to sanitize
* @return {String} The santized string
*/
_shellEscape(arg) {
if(typeof arg === 'number') return arg;
return arg.split(' ')[0].replace(/[^A-Z0-9.]/ig, '');
}
}
module.exports = new WindowsCPU();