UNPKG

2.29 kBJavaScriptView Raw
1const exec = require('child_process').exec;
2
3/**
4 * Task killer. Kill hanged drivers
5 * @type {TaskKiller}
6 */
7class TaskKiller {
8
9 /**
10 * Kill hang driver
11 * @param {Array<string>} itemToKill - list of items to kill
12 * @return {Promise<void>} - promise that resolves after killing drivers
13 */
14 static kill(itemToKill) {
15 const CMD_LIST = "tasklist /V /FO CSV";
16 const KILL = "taskkill /F /PID ";
17
18 return new Promise((resolve, reject) => {
19 exec(CMD_LIST, (error, stdout) => {
20 if (error) reject(error);
21
22 stdout
23 .split("\r\n")
24 .filter(process => itemToKill.find(item => process.includes(item)))
25 .map(item => item.split(/,/)[1].replace(/"/g, ""))
26 .forEach(pid => exec(KILL + pid, error => {
27 if (error) reject(error);
28 console.log("Process with id " + pid + " killed");
29 }));
30
31 resolve();
32 })
33 });
34 }
35
36 static killWebdriver(port) {
37 const CMD_LIST = "netstat -ano | findstr \":" + port + "\"";
38 const KILL = "taskkill /F /PID ";
39
40 return new Promise((resolve, reject) => {
41 exec(CMD_LIST, (error, stdout) => {
42 if (error) {
43 if (error.message.includes("Command failed")) {
44 resolve()
45 } else {
46 reject(error);
47 }
48 }
49
50 if (stdout) {
51 const processRecord = stdout
52 .split("\r\n")
53 .find(process => process.includes(":" + port));
54
55 if (processRecord) {
56 const splitProcessRecord = processRecord.split(/\s+/g);
57 const pid = splitProcessRecord[splitProcessRecord.length - 1];
58 exec(KILL + pid, error => {
59 if (error) reject(error);
60 console.log("Process with id " + pid + " killed");
61 })
62 }
63 }
64
65 resolve();
66 })
67 });
68 }
69}
70
71module.exports = TaskKiller;
\No newline at end of file