buncid/utils/kill-child.ts
Benjamin Toby 7e320c87f5 Updates
2025-02-22 18:02:00 +01:00

75 lines
1.9 KiB
TypeScript
Executable File

import { ChildProcess } from "child_process";
import colors from "./console-colors";
import killPort from "kill-port";
/**
* ## Kill Child Process Function
* @param {string | number | (string | number)[]} [port]
* @returns {Promise<boolean>}
*/
export default async function killChild(
/**
* Child Process to be killed
*/
childProcess?: ChildProcess,
/**
* Port/ports to be killed
*/
port?: string | number | (string | number)[]
): Promise<boolean> {
if (!childProcess) return false;
try {
const childKilled = childProcess.kill();
if (childKilled) {
return true;
} else {
return await killPortFn(childProcess, port);
}
} catch (error: any) {
await killPortFn(childProcess, port);
console.log(
`${colors.FgRed}Error:${colors.Reset} Child Process couldn't be killed! ${error.message}`
);
return false;
}
}
async function killPortFn(
/**
* Child Process to be killed
*/
childProcess?: ChildProcess,
/**
* Port/ports to be killed
*/
port?: string | number | (string | number)[]
): Promise<boolean> {
if (!childProcess) return false;
try {
if (typeof port == "object" && port?.[0]) {
for (let i = 0; i < port.length; i++) {
const singlePort = port[i];
await killPort(Number(singlePort), "tcp");
}
childProcess.kill();
return true;
} else if (port) {
await killPort(Number(port), "tcp");
childProcess.kill();
return true;
} else {
return false;
}
} catch (_err: any) {
console.log(
`${colors.FgRed}Error:${colors.Reset} Child Process PORT couldn't be killed! ${_err.message}`
);
return false;
}
}