dsql-admin/dsql-app/utils/backend/killProcessOnPort.js

69 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-11-05 11:12:42 +00:00
// @ts-check
const { execSync } = require("child_process");
/**
*
* @param {number | string | null | undefined} port
* @returns
*/
module.exports = async function killProcessOnPort(port) {
if (!port) {
console.error("Error: No port specified");
return;
}
const targetPort = parseInt(port.toString());
if (isNaN(targetPort)) {
console.error("Error: Port must be a number");
return;
}
if (typeof targetPort !== "number") {
console.error("Error: Port must be a number");
return;
}
const processId = (() => {
try {
if (process.platform.match(/win/i)) {
const readNetStat = execSync(
`netstat -ano | findstr :${targetPort}`
).toString("utf-8");
const firstLine = readNetStat.match(/.*/)?.[0].trim();
const PID = firstLine?.split(" ").at(-1);
return PID;
}
return execSync(
`lsof -i :${targetPort} | awk '$1 == "COMMAND" { next } { print $2 }'`
)
.toString()
.trim();
} catch (/** @type {any} */ error) {
console.log(
`Error finding PID on ${process.platform}:`,
error.message
);
return null;
}
})();
if (!processId) {
console.error(`Error: No process found on port ${targetPort}`);
return;
}
try {
if (process.platform.match(/win/i)) {
execSync(`taskkill /F /PID ${processId} /T`);
} else {
execSync(`kill -9 ${processId}`);
}
console.log(`Killed process ${processId} on port ${targetPort}`);
} catch (/** @type {any} */ error) {
console.error("Error:", error.message);
}
};