一分钟编写一个全局npm命令脚本-杀死占用端口的所有进程

221 阅读1分钟

kill-port(杀死占用端口的所有进程)

项目背景:

单点登录的子项目开发的时候需要粘贴token,如果程序卡顿就会出现a端口被占用,而我们已经粘贴过token到a端口,这时候我们希望快速杀死a端口,常规思路是会执行

netstat -ano | findstr :${port}
taskkill /PID ${pid} /F
taskkill /PID ${pid} /F

来杀死端口,如果进程占用较多还会比较繁琐。

实现步骤

全局实现kill 命令来杀死某个端口

创建项目结构

创建项目package.json

npm init 

img转存失败,建议直接上传图片文件

package.json文件,并需要新增bin 自定义指令,以便于后续可以使用kill命令直接杀死进程

{

 "name": "kill-port",

 "version": "1.0.0",

 "description": "一个用来杀死占用某端口所有进程的脚本命令",

 "main": "index.js",

 "bin": {

  "kill": "./index.js"

 },

 "scripts": {

  "test": "node index.js"

 },

 "author": "2876920450@qq.com",

 "license": "ISC"

}

创建主函数文件index (test)

在index头部需要加上

#!/usr/bin/env node
console.log('欢迎使用端口号查找工具');

注册全局kill-port 应用

在文件夹目录命令行使用下面命令注册全局kill-port 应用

npm install -g .

执行kill命令

然后执行kill命令能够正常打印

kill

主函数源码

#!/usr/bin/env node
const process = require('process');
const os = require('os');
const { execSync } = require('child_process');
const main=()=>{
  const port = process.argv[2];
console.log(port,"port");
 const isWindows = os.type() === 'Windows_NT';
   try {
    console.log(`正在查找占用端口 ${port}的进程...`);
    let command;
    if (isWindows) {
      command = `netstat -ano | findstr :${port}`;
    } else {
      command = `lsof -i :${port}`;
    }
    const result = execSync(command).toString();
    if (result.trim() === '') {
      console.log(`No process is using port ${port}.`);
      process.exit(0);
    }

    let pids = [];
    if (isWindows) {
      const lines = result.split('\n');
      for (const line of lines) {
        if (line.includes(':') && (line.includes('LISTENING') || line.includes('ESTABLISHED'))) {
          const match = line.match(/\s(\d+)\s$/);
          if (match) {
            const pid = match[1];
            if (pid && !isNaN(pid)) {
              pids.push(pid);
            }
          }
        }
      }
    } else {
      const lines = result.split('\n');
      for (const line of lines) {
        if (!line.startsWith('COMMAND')) {
          const parts = line.split(/\s+/);
          const pid = parts[1];
          if (pid && !isNaN(pid)) {
            pids.push(pid);
          }
        }
      }
    }

    if (pids.length === 0) {
      console.log(`No process is using port ${port}.`);
      process.exit(0);
    }

    console.log(`Found processes using port ${port}: ${pids.join(', ')}`);
    console.log('Attempting to kill these processes...');

    pids.forEach(pid => {
      try {
        if (isWindows) {
          execSync(`taskkill /PID ${pid} /F`);
        } else {
          execSync(`kill -9 ${pid}`);
        }
        console.log(`Successfully killed process with PID: ${pid}`);
      } catch (error) {
        console.error(`Failed to kill process with PID ${pid}: ${error.message}`);
      }
    });

  } catch (error) {
    console.error(`Error: ${error.message}`);
    console.error(`未发现占用端口 ${port}的进程`);

    process.exit(1);
  }
}
main()