forked from sindresorhus/tasklist
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (62 loc) · 1.61 KB
/
index.js
File metadata and controls
76 lines (62 loc) · 1.61 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict';
const {promisify} = require('util');
const childProcess = require('child_process');
const neatCsv = require('neat-csv');
const sec = require('sec');
const execFile = promisify(childProcess.execFile);
module.exports = async (options = {}) => {
if (process.platform !== 'win32') {
throw new Error('Windows only');
}
const args = ['/nh', '/fo', 'csv'];
if (options.verbose) {
args.push('/v');
}
if (options.system && options.username && options.password) {
args.push(
'/s', options.system,
'/u', options.username,
'/p', options.password
);
}
if (Array.isArray(options.filter)) {
for (const filter of options.filter) {
args.push('/fi', filter);
}
}
const defaultHeaders = [
'imageName',
'pid',
'sessionName',
'sessionNumber',
'memUsage'
];
const verboseHeaders = defaultHeaders.concat([
'status',
'username',
'cpuTime',
'windowTitle'
]);
const headers = options.verbose ? verboseHeaders : defaultHeaders;
let res;
let stdout = null;
try {
res = await execFile('tasklist', args, {windowsHide: true});
stdout = res.stdout;
} catch (e) {
res = await execFile(process.env.windir + '\\system32\\tasklist', args);
stdout = res.stdout;
}
// Not start with `"` means no matching tasks. See #11.
const data = stdout.startsWith('"') ? await neatCsv(stdout, {headers}) : [];
return data.map(task => {
// Normalize task props
task.pid = Number(task.pid);
task.sessionNumber = Number(task.sessionNumber);
task.memUsage = Number(task.memUsage.replace(/[^\d]/g, '')) * 1024;
if (options.verbose) {
task.cpuTime = sec(task.cpuTime);
}
return task;
});
};