Skip to content

Instantly share code, notes, and snippets.

@shospodarets
Created December 18, 2016 16:28
Show Gist options
  • Save shospodarets/0a6e1d528b32c1be6c4390b6ab234180 to your computer and use it in GitHub Desktop.
Save shospodarets/0a6e1d528b32c1be6c4390b6ab234180 to your computer and use it in GitHub Desktop.
Script takes the port as a param and tries to find and kill a process which is listening the port, e.g. `node killProcessByPort.js 8080`
#!/usr/bin/env node
/**
* Script takes the port as a param and tries to find and kill a process
* which is listening the port
*
* Example of the script usage:
* node SCRIPT %PORT_NUMBER%
*/
// VARS
const port = process.argv[2]; // taking line argument
if (!port) {
throw new Error('The script expects the port number sent via param');
}
// HELPERS
/**
* Executes the command with the arguments
* @param cmd {String}
* @param args {String}
* @param callback {Function}
*/
function runExecCommand(cmd, args, callback) {
exec(
`${cmd} ${args}`,
(err, stdout/*, stderr*/) => {
if (err) {
callback(1, err);
} else {
callback(0, stdout);
}
});
}
function killPyPort({
getPIDByPortCommand,
getKillCommandFromOutput
}) {
// execute the find PID command
return runExecCommand(
getPIDByPortCommand,
'',
(code, data) => {
if (code !== 0) {
console.error(`Couldn't find a process on the port: ${port}`, data);
return;
}
if (!data) {
console.log(`Couldn't find a process on the port: ${port}`);
return;
}
// execute the kill command
runExecCommand(
getKillCommandFromOutput(data),
'',
(_code, _data) => {
if (_code !== 0) {
console.error(`Couldn't kill a process on the port: ${port}`, _data);
return;
}
console.log(`Done`);
}
);
}
);
}
// INIT
if (process.platform === 'win32') {// WINDOWS
// http://stackoverflow.com/a/35312370
killPyPort({
getPIDByPortCommand: `echo off & (for /f "tokens=5" %a in ('netstat -aon ^| findstr ${port}') do echo "%a") & echo on`,
getKillCommandFromOutput: (output) => {
const PID = output.split('\n')[0];// the first line only
return `taskkill /F /PID ${PID}`;
}
});
} else {// NON WINDOWS
// http://stackoverflow.com/a/16583477
killPyPort({
getPIDByPortCommand: `lsof -P | grep ':'${port} | awk '{print $2}'`,
getKillCommandFromOutput: (output) => {
//noinspection UnnecessaryLocalVariableJS
const PID = output;// output is the PID actually
return `kill -9 ${PID}`;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment