1/*
2 * Copyright (C) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16const { spawn } = require('child_process');
17const iconv = require('iconv-lite');
18
19module.exports = {
20    getNodePIDs,
21    deleteNodePIDs
22};
23
24async function getNodePIDs() {
25    return new Promise((resolve, reject) => {
26        const tasklist = spawn('tasklist', [
27            '/nh',
28            '/fo',
29            'csv',
30            '/fi',
31            'imagename eq node.exe'
32        ]);
33        let output = '';
34
35        tasklist.stdout.on('data', (data) => {
36            output += iconv.decode(data, 'cp936');
37        });
38
39        tasklist.on('close', () => {
40            try {
41                const lines = output.trim().split('\r\n');
42                const pids = lines.filter(line => line.trim())
43                    .map(line => {
44                        const parts = line.split(/","/);
45                        return parts[1].replace(/^"|"$/g, '');
46                    });
47                resolve(pids);
48            } catch (error) {
49                reject(error);
50            }
51        });
52
53        tasklist.stderr.on('data', (data) => {
54            reject(new Error(`Error getting PIDs: ${data}`));
55        });
56    });
57}
58
59async function deleteNodePIDs(PIDs) {
60    return new Promise((resolve, reject) => {
61        PIDs.forEach(item => {
62            const deleteProcess = spawn('taskkill', [
63                '/f',
64                '/pid',
65                item,
66            ], { shell: true });
67
68            if (!deleteProcess) {
69                console.error(new Error("Failed to delete child process"));
70            }
71
72            let stdout;
73            let stderr;
74
75            deleteProcess.stdout.on('data', data => {
76                stdout += data.toString();
77            });
78
79            deleteProcess.stderr.on('data', data => {
80                stderr += data.toString();
81                console.error(data.toString());
82            });
83
84            deleteProcess.on('close', code => {
85                if (code !== 0) {
86                    console.error(`delete process error exited with code ${code}`);
87                    reject(code);
88                } else {
89                    resolve(code);
90                }
91            });
92        });
93    });
94}