UNPKG

cross-port-killer

Version:

Kill the process running on a given TCP port on Windows, Linux and Mac

73 lines (72 loc) 2.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Killer = void 0; var child_process_1 = require("child_process"); var Killer = /** @class */ (function () { function Killer(platform) { this.platforms = { win32: { command: 'Taskkill', args: ['/F', '/PID'] }, linux: { command: 'kill', args: ['-9'] }, darwin: { command: 'kill', args: ['-9'] }, }; this.platform = platform; } Killer.prototype.kill = function (port) { return this[this.platform](port); }; Killer.prototype.killByPid = function (pid) { return this.killByPids([pid]); }; Killer.prototype.killByPids = function (pids) { var _a = this.platforms[process.platform], command = _a.command, args = _a.args; var result = pids.filter(function (pid) { return (0, child_process_1.spawnSync)(command, args.concat(pid)).status === 0; }); return Promise.resolve(result); }; Killer.prototype.darwin = function (port) { return this.linux(port); }; Killer.prototype.linux = function (port) { var _this = this; var resolver; var promise = new Promise(function (resolve) { return (resolver = resolve); }); var lsof = (0, child_process_1.spawn)('lsof', ['-s', 'TCP:LISTEN', '-i', ':' + port]); var awk = (0, child_process_1.spawn)('awk', ['$8 == "TCP" { print $2 }'], { stdio: [lsof.stdout], }); var result = ''; awk.stdout.on('data', function (data) { return (result += data); }); awk.on('close', function () { return _this.parse(result, resolver); }); if (awk.stdin) { awk.stdin.end(); } return promise; }; Killer.prototype.win32 = function (port) { var _this = this; var resolver, promise = new Promise(function (resolve) { resolver = resolve; }); var findstr = (0, child_process_1.spawn)('findstr', [":".concat(port, ".*")], { stdio: ['pipe'], }); var netstat = (0, child_process_1.spawn)('netstat', ['-ano'], { stdio: ['ignore', findstr.stdin], }); var result = ''; findstr.stdout.on('data', function (data) { return (result += data); }); findstr.on('close', function () { return _this.parse(result, resolver); }); findstr.stdin.end(); return promise; }; Killer.prototype.parse = function (data, resolver) { var pids = data.trim().match(/\d+$/gm); if (pids && pids.length) { return this.killByPids(pids).then(function (killed) { return resolver(killed); }); } resolver([]); }; return Killer; }()); exports.Killer = Killer;