@chengyixu/port-kill 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +15 -0
  2. package/src/index.js +53 -0
package/package.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "@chengyixu/port-kill",
3
+ "version": "1.0.0",
4
+ "description": "Find and kill processes on a port. Cross-platform, zero dependencies.",
5
+ "main": "src/index.js",
6
+ "bin": {
7
+ "port-kill": "./src/index.js"
8
+ },
9
+ "files": ["src/"],
10
+ "keywords": ["port", "kill", "process", "pid", "lsof", "netstat", "cli"],
11
+ "author": "chengyixu",
12
+ "license": "MIT",
13
+ "repository": "chengyixu/port-kill",
14
+ "engines": { "node": ">=18" }
15
+ }
package/src/index.js ADDED
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ const { execSync } = require('child_process');
3
+ const os = require('os');
4
+
5
+ const port = process.argv[2];
6
+ const signal = process.argv[3] || 'SIGTERM';
7
+
8
+ if (!port || isNaN(port)) {
9
+ console.error('Usage: port-kill <port> [signal]');
10
+ console.error('Example: port-kill 3000');
11
+ console.error('Example: port-kill 8080 SIGKILL');
12
+ process.exit(1);
13
+ }
14
+
15
+ function findPid(port) {
16
+ const platform = os.platform();
17
+ try {
18
+ if (platform === 'win32') {
19
+ const out = execSync(`netstat -ano | findstr :${port}`, { encoding: 'utf8' });
20
+ const match = out.match(/LISTENING\s+(\d+)/);
21
+ return match ? parseInt(match[1]) : null;
22
+ } else {
23
+ // macOS / Linux
24
+ let cmd;
25
+ try {
26
+ execSync('command -v lsof', { stdio: 'ignore' });
27
+ cmd = `lsof -ti tcp:${port}`;
28
+ } catch {
29
+ cmd = `ss -tlnp 'sport = :${port}' | awk '/LISTEN/{split($NF,a,","); gsub(/[^0-9]/,\"\",a[1]); print a[1]}'`;
30
+ }
31
+ const out = execSync(cmd, { encoding: 'utf8' }).trim();
32
+ if (!out) return null;
33
+ return parseInt(out.split('\n')[0]);
34
+ }
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ const pid = findPid(port);
41
+
42
+ if (!pid) {
43
+ console.log(`No process found on port ${port}`);
44
+ process.exit(0);
45
+ }
46
+
47
+ try {
48
+ process.kill(pid, signal);
49
+ console.log(`Killed process ${pid} on port ${port} (${signal})`);
50
+ } catch (err) {
51
+ console.error(`Failed to kill PID ${pid}: ${err.message}`);
52
+ process.exit(1);
53
+ }