├── .gitignore ├── .nvmrc ├── README.md ├── backlog.md ├── cli.js ├── dist └── index.js ├── docs ├── PortClient.html ├── fonts │ ├── OpenSans-Bold-webfont.eot │ ├── OpenSans-Bold-webfont.svg │ ├── OpenSans-Bold-webfont.woff │ ├── OpenSans-BoldItalic-webfont.eot │ ├── OpenSans-BoldItalic-webfont.svg │ ├── OpenSans-BoldItalic-webfont.woff │ ├── OpenSans-Italic-webfont.eot │ ├── OpenSans-Italic-webfont.svg │ ├── OpenSans-Italic-webfont.woff │ ├── OpenSans-Light-webfont.eot │ ├── OpenSans-Light-webfont.svg │ ├── OpenSans-Light-webfont.woff │ ├── OpenSans-LightItalic-webfont.eot │ ├── OpenSans-LightItalic-webfont.svg │ ├── OpenSans-LightItalic-webfont.woff │ ├── OpenSans-Regular-webfont.eot │ ├── OpenSans-Regular-webfont.svg │ └── OpenSans-Regular-webfont.woff ├── index.html ├── index.js.html ├── scripts │ ├── linenumber.js │ └── prettify │ │ ├── Apache-License-2.0.txt │ │ ├── lang-css.js │ │ └── prettify.js └── styles │ ├── jsdoc-default.css │ ├── prettify-jsdoc.css │ └── prettify-tomorrow.css ├── example.js ├── image.png ├── index.js ├── package.json ├── pnpm-lock.yaml ├── src ├── index.ts └── shell-exec.d.ts ├── test └── portClient.test.js └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Node.js 2 | node_modules/ 3 | npm-debug.log 4 | yarn-debug.log 5 | yarn-error.log 6 | 7 | # Build directories 8 | build/ 9 | 10 | # SCSS and Sass files 11 | *.css.map 12 | *.scssc 13 | 14 | # IDEs and Editors 15 | .vscode/ 16 | .idea/ 17 | *.sublime-workspace 18 | 19 | # Operating system files 20 | .DS_Store 21 | 22 | # Package-lock.json or Yarn lock file 23 | package-lock.json 24 | yarn.lock 25 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 16.0.0 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![alt text](image.png) 2 | # Port Client 3 | 4 | The `Port Client` class offers a **killer feature**: **fast operations**. 5 | 6 | ## Table of Contents 7 | 8 | 1. [Overview](#overview) 9 | 2. [Command-Line Interface (CLI) Usage](#cli-usage) 10 | 3. [Class Constructor](#class-constructor) 11 | 4. [Usage Example](#usage-example) 12 | 13 | ## Overview 14 | 15 | The `Port Client` class allows users to interact with network ports, providing functionalities to check whether a port is active, kill a port, and verify the existence of ports. It supports both **TCP** and **UDP** protocols, works on multiple platforms (Windows and Unix-like systems), and includes a `dryRun` mode for testing. 16 | 17 | ### Key Feature: **Fast Operations** 18 | 19 | The `--fast` flag for the CLI or the `speed: 'fast'` option for the script provides **fast operations**. This option makes port operations significantly faster by bypassing slower checks like listing all active ports. It's particularly useful when you need to check or kill ports quickly. 20 | 21 | When using the `--fast` flag or `speed: 'fast'`, the script will skip certain checks and perform actions directly on the specified ports. 22 | 23 | ### Parameters: 24 | 25 | - `ports`: The port(s) to operate on (either a number, an array, or a range). 26 | - `options`: Configuration options for the port operation, such as action (`check`, `kill`), protocol (`tcp` or `udp`), speed (`safe` or `fast`), and interactive mode. 27 | 28 | ## Command-Line Interface (CLI) Usage 29 | 30 | You can also use the `Port Client` class via a command-line interface by calling it from a `cli.js` script. This allows you to interact with the ports directly from your terminal. 31 | 32 | ### Running the CLI 33 | 34 | 1. **To check port(s)**: 35 | 36 | ``` 37 | npx port-client 3000 38 | ``` 39 | 40 | 2. **To kill a port(s)**: 41 | 42 | ``` 43 | npx port-client 3000 --kill 44 | ``` 45 | 46 | This script accepts a list of ports followed by an action (`check` or `kill`). The ports will be parsed, and the specified action will be executed. 47 | 48 | ### Fast Operation Flag 49 | 50 | You can enable **fast operations** in the CLI by using the `--fast` flag: 51 | 52 | ``` 53 | npx port-client 3000 check --fast 54 | ``` 55 | 56 | This will perform the operation 100 times faster by skipping extra checks. 57 | 58 | ## Class Constructor 59 | 60 | The constructor of the `Port Client` class initializes an instance with the ports and options for the port operation. Below are the parameters available for the constructor. 61 | 62 | ### Constructor Parameters: 63 | - `ports`: The port(s) to operate on (either a number, an array, or a range). 64 | - `options`: Configuration options for the port operation. The available options are: 65 | - `action`: Action to perform on the port(s) (`check`, `kill`, `isExist`). Default is `check`. 66 | - `method`: The protocol method to use (`tcp` or `udp`). Default is `tcp`. 67 | - `interactive`: Whether to enable interactive mode for selecting ports. Default is `false`. 68 | - `dryRun`: If `true`, no actual changes are made (dry run). Default is `false`. 69 | - `verbose`: If `true`, enables verbose logging. Default is `false`. 70 | - `graceful`: If `true`, uses graceful termination for killing ports. Default is `false`. 71 | - `filter`: A filter for limiting results. Default is `null`. 72 | - `range`: A range of ports to check. Default is `null`. 73 | - `speed`: The speed mode to use (`safe` or `fast`). Default is `safe`. 74 | 75 | ### Example Usage: 76 | ```js 77 | import port from 'port-client'; 78 | 79 | const ports = [8080, 3000]; 80 | const options = { 81 | action: 'check', // Action to perform 82 | method: 'tcp', // Protocol method 83 | interactive: true, // Enable interactive mode 84 | dryRun: false, // Dry run (no actual changes) 85 | verbose: true, // Enable verbose logging 86 | graceful: true, // Use graceful kill 87 | speed: 'safe', // Safe speed mode (default) 88 | }; 89 | 90 | const port = new port(ports, options); 91 | port.execute() 92 | .then(() => console.log('Port operations complete.')) 93 | .catch((error) => console.error('Error during port operations:', error)); 94 | ``` 95 | 96 | ## Conclusion 97 | 98 | The `Port Client` class offers a flexible and interactive way to manage ports, whether you're checking if they're active, killing processes associated with them, or performing dry runs to preview actions. It can be used in a Node.js script or directly in the shell using the provided CLI script. 99 | 100 | ## Connect with Me: 101 | - [LinkedIn - Vitalii Semianchuk](https://www.linkedin.com/in/vitalii-semianchuk-9812a786/) 102 | - [Telegram - @jsmentorfree](https://t.me/jsmentorfree) - We do a lot of free teaching on this channel! Join us to learn and grow in web development. 103 | - [Tiktok - @jsmentoring](https://www.tiktok.com/@jsmentoring) Everyday new videos 104 | - [Youtube - @jsmentor-uk](https://www.youtube.com/@jsmentor-uk) Mentor live streams 105 | - [Dev.to - fix2015](https://dev.to/fix2015) Javascript featured, live, experience 106 | -------------------------------------------------------------------------------- /backlog.md: -------------------------------------------------------------------------------- 1 | - Move on typescript (done) 2 | - check func for watch for port (in process) 3 | - show view of users (in process) 4 | - use tags (done) 5 | - add logs (in process) 6 | - create video on tiktok 7 | - create story hackertoon 8 | - make story for linkedin 9 | -------------------------------------------------------------------------------- /cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 'use strict'; 3 | 4 | /** 5 | * Module dependencies. 6 | */ 7 | const portUtil = require('./dist/index.js'); 8 | const getThemArgs = require('get-them-args'); 9 | 10 | /** 11 | * Parse command-line arguments. 12 | */ 13 | const args = getThemArgs(process.argv.slice(2)); 14 | 15 | /** 16 | * Verbose mode for logging. 17 | * @type {boolean} 18 | */ 19 | const verbose = args.verbose || false; 20 | 21 | /** 22 | * Ports to process, extracted from arguments. 23 | * @type {Array|string} 24 | */ 25 | let port = args.port ? args.port.toString().split(',') : args.unknown; 26 | 27 | /** 28 | * Method to use for processing (e.g., 'tcp'). 29 | * @type {string} 30 | */ 31 | const method = args.method || 'tcp'; 32 | 33 | /** 34 | * Speed mode: 'fast' or 'safe'. 35 | * @type {string} 36 | */ 37 | const speed = args.speed || args.fast ? 'fast' : 'safe'; 38 | 39 | /** 40 | * Interactive mode toggle. 41 | * @type {boolean} 42 | */ 43 | const interactive = args.interactive || false; 44 | 45 | /** 46 | * Dry-run mode toggle. 47 | * @type {boolean} 48 | */ 49 | const dryRun = args.dryRun || false; 50 | 51 | /** 52 | * Graceful handling toggle. 53 | * @type {boolean} 54 | */ 55 | const graceful = args.graceful || false; 56 | 57 | /** 58 | * Filter criteria for processing ports. 59 | * @type {string} 60 | */ 61 | const filter = args.filter || ''; 62 | 63 | /** 64 | * Range of ports for processing, if applicable. 65 | * @type {string|null} 66 | */ 67 | const range = args.filter || null; 68 | 69 | /** 70 | * Action to perform: 'kill' or other specified action. 71 | * @type {string} 72 | */ 73 | const action = args.kill ? 'kill' : args.action || 'check'; 74 | 75 | /** 76 | * Ensure port is an array for consistent processing. 77 | */ 78 | if (!Array.isArray(port)) { 79 | port = [port]; 80 | } 81 | 82 | /** 83 | * Process each port using portUtil with the specified options. 84 | */ 85 | Promise.all( 86 | port.map((current) => { 87 | return portUtil(current, { 88 | method, 89 | speed, 90 | action, 91 | interactive, 92 | dryRun, 93 | verbose, 94 | graceful, 95 | filter, 96 | range 97 | }) 98 | .then((result) => { 99 | verbose && console.log(`Process on port ${action} ${current}`); 100 | }) 101 | .catch((error) => { 102 | verbose && console.log(`Could not process on port ${current}. ${error.message}.`); 103 | }); 104 | }) 105 | ); 106 | -------------------------------------------------------------------------------- /dist/index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 4 | return new (P || (P = Promise))(function (resolve, reject) { 5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 8 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 9 | }); 10 | }; 11 | var __importDefault = (this && this.__importDefault) || function (mod) { 12 | return (mod && mod.__esModule) ? mod : { "default": mod }; 13 | }; 14 | Object.defineProperty(exports, "__esModule", { value: true }); 15 | const shell_exec_1 = __importDefault(require("shell-exec")); 16 | const readline_1 = __importDefault(require("readline")); 17 | class PortClient { 18 | constructor(ports, { method = 'tcp', action = 'check', interactive = false, dryRun = false, verbose = false, graceful = false, filter = null, range = null, speed = 'safe', } = {}) { 19 | this.ports = ports; 20 | this.method = method; 21 | this.action = action; 22 | this.interactive = interactive; 23 | this.dryRun = dryRun; 24 | this.verbose = verbose; 25 | this.graceful = graceful; 26 | this.filter = filter; 27 | this.range = range; 28 | this.speed = speed; 29 | this.platform = process.platform; 30 | } 31 | log(message) { 32 | if (this.verbose) { 33 | console.log(message); 34 | } 35 | } 36 | parsePorts() { 37 | if (Array.isArray(this.ports)) { 38 | return this.ports.map(Number).filter(Boolean); 39 | } 40 | else if (this.range) { 41 | const [start, end] = this.range.split('-').map(Number); 42 | return Array.from({ length: end - start + 1 }, (_, i) => start + i); 43 | } 44 | else { 45 | const port = Number(this.ports); 46 | return port ? [port] : []; 47 | } 48 | } 49 | execute() { 50 | return __awaiter(this, void 0, void 0, function* () { 51 | const parsedPorts = this.parsePorts(); 52 | if (parsedPorts.length === 0) { 53 | throw new Error('Invalid or no port(s) provided.'); 54 | } 55 | if (this.dryRun) { 56 | this.success(`Dry run: Ports to operate on - ${parsedPorts.join(', ')}`); 57 | return; 58 | } 59 | if (this.interactive) { 60 | const activePorts = yield this.listActivePorts(); 61 | const selectedPorts = yield this.promptUserToSelectPorts(activePorts); 62 | return this.handlePorts(selectedPorts.map(Number)); // Ensure it's a number[] 63 | } 64 | return this.handlePorts(parsedPorts); 65 | }); 66 | } 67 | handlePorts(ports) { 68 | return __awaiter(this, void 0, void 0, function* () { 69 | switch (this.action) { 70 | case 'check': 71 | case 'isExist': 72 | return this.showPortInfo(ports); 73 | case 'kill': 74 | return this.killPorts(ports); 75 | default: 76 | throw new Error(`Unknown action: ${this.action}`); 77 | } 78 | }); 79 | } 80 | listActivePorts() { 81 | return __awaiter(this, void 0, void 0, function* () { 82 | const command = this.platform === 'win32' 83 | ? 'netstat -nao' 84 | : (this.speed === 'fast' 85 | ? `lsof -i :${this.ports}` 86 | : 'lsof -i -P -n'); 87 | try { 88 | const { stdout } = yield (0, shell_exec_1.default)(command); 89 | const lines = stdout.split('\n'); 90 | return this.platform === 'win32' ? this.parseWindowsPorts(lines) : this.parseUnixPorts(lines); 91 | } 92 | catch (error) { 93 | throw new Error(`Failed to list active ports: ${error.message}`); 94 | } 95 | }); 96 | } 97 | parseWindowsPorts(lines) { 98 | const regex = new RegExp(`^ *${this.method.toUpperCase()} *[^ ]*:(\\d+),`, 'gm'); 99 | return lines.reduce((acc, line) => { 100 | const match = line.match(regex); 101 | if (match && match[1] && !acc.includes(match[1])) { 102 | acc.push(match[1]); 103 | } 104 | return acc; 105 | }, []); 106 | } 107 | parseUnixPorts(lines) { 108 | const regex = /(?<=:\d{1,5})->|\b\d{1,5}(?=->|\s+\(CLOSED\)|\s+\(ESTABLISHED\)|\s+\(LISTEN\))/g; 109 | return lines.flatMap((line) => line.match(regex) || []).filter(Boolean); 110 | } 111 | promptUserToSelectPorts(activePorts) { 112 | return __awaiter(this, void 0, void 0, function* () { 113 | return new Promise((resolve) => { 114 | const rl = readline_1.default.createInterface({ input: process.stdin, output: process.stdout }); 115 | activePorts.forEach((port, index) => { 116 | this.success(`${index + 1}. ${port}`); 117 | }); 118 | rl.question('Select ports to operate on (comma-separated indices): ', (answer) => { 119 | const indices = answer.split(',').map(Number); 120 | const selectedPorts = indices.map((index) => activePorts[index - 1]).filter(Boolean); 121 | rl.close(); 122 | resolve(selectedPorts.map(Number)); // Ensure it's a number[] 123 | }); 124 | }); 125 | }); 126 | } 127 | success(message) { 128 | console.log('\x1b[32m%s\x1b[0m', `${message}`); 129 | } 130 | error(message) { 131 | console.log('\x1b[31m%s\x1b[0m', `${message}`); 132 | } 133 | showPortInfo(ports) { 134 | return __awaiter(this, void 0, void 0, function* () { 135 | for (const port of ports) { 136 | try { 137 | const isActive = yield this.checkPortStatus(port); 138 | this.success(isActive ? `Port ${port} is active.` : `Port ${port} is not active.`); 139 | } 140 | catch (error) { 141 | this.error(`Error checking port ${port}: ${error.message}`); 142 | } 143 | } 144 | }); 145 | } 146 | isExistFast(port) { 147 | return __awaiter(this, void 0, void 0, function* () { 148 | // Fast method: using lsof (this is an example, you can replace with your own fast method) 149 | try { 150 | const { stdout } = yield (0, shell_exec_1.default)(`lsof -i tcp:${port}`); 151 | return stdout.trim().length > 0; 152 | } 153 | catch (error) { 154 | return false; 155 | } 156 | }); 157 | } 158 | checkPortStatus(port) { 159 | return __awaiter(this, void 0, void 0, function* () { 160 | const checkMethod = this.speed === 'fast' ? this.isExistFast : this.isExistNormal; 161 | return yield checkMethod.call(this, port); 162 | }); 163 | } 164 | killPorts(ports) { 165 | return __awaiter(this, void 0, void 0, function* () { 166 | for (const port of ports) { 167 | try { 168 | const command = this.platform === 'win32' 169 | ? yield this.getWindowsKillCommand(port) 170 | : yield this.getUnixKillCommand(port, this.method, this.graceful); 171 | this.log(`Executing: ${command}`); 172 | const result = yield (0, shell_exec_1.default)(command); 173 | this.success(`Successfully killed port ${port} ${result.stdout}`); 174 | } 175 | catch (error) { 176 | this.error(`Failed to kill port ${port}: ${error.message}`); 177 | } 178 | } 179 | }); 180 | } 181 | getWindowsKillCommand(port) { 182 | return __awaiter(this, void 0, void 0, function* () { 183 | try { 184 | const { stdout } = yield (0, shell_exec_1.default)('netstat -nao'); 185 | const lines = stdout.split('\n'); 186 | const regex = new RegExp(`^ *${this.method.toUpperCase()} *[^ ]*:${port},`, 'gm'); 187 | const linesWithPort = lines.filter((line) => regex.test(line)); 188 | const pids = linesWithPort.reduce((acc, line) => { 189 | const pidMatch = line.match(/(\d+)\w*/); 190 | if (pidMatch) 191 | acc.push(pidMatch[1]); 192 | return acc; 193 | }, []); 194 | return `TaskKill /F /PID ${pids.join(' /PID ')}`; 195 | } 196 | catch (error) { 197 | throw new Error(`Failed to get Windows kill command: ${error.message}`); 198 | } 199 | }); 200 | } 201 | getUnixKillCommand(port_1) { 202 | return __awaiter(this, arguments, void 0, function* (port, method = 'tcp', graceful = false) { 203 | const baseCommand = this.buildBaseCommand(method, port); 204 | const killCommand = graceful ? 'kill' : 'kill -9'; 205 | try { 206 | const processExists = yield this.checkIfProcessExists(port); 207 | if (!processExists) { 208 | throw new Error('No process running on port'); 209 | } 210 | return `${baseCommand} ${killCommand}`; 211 | } 212 | catch (error) { 213 | throw new Error(`${error.message}`); 214 | } 215 | }); 216 | } 217 | isExistNormal(port) { 218 | return __awaiter(this, void 0, void 0, function* () { 219 | // Normal method: using netstat (this is an example, you can replace with your own normal method) 220 | try { 221 | const { stdout } = yield (0, shell_exec_1.default)(`netstat -na | grep :${port}`); 222 | return stdout.trim().length > 0; 223 | } 224 | catch (error) { 225 | return false; 226 | } 227 | }); 228 | } 229 | buildBaseCommand(method, port) { 230 | return `lsof -t -i ${method}:${port}`; 231 | } 232 | checkIfProcessExists(port) { 233 | return __awaiter(this, void 0, void 0, function* () { 234 | try { 235 | const { stdout } = yield (0, shell_exec_1.default)(`lsof -t -i tcp:${port}`); 236 | return stdout.trim().length > 0; 237 | } 238 | catch (error) { 239 | throw new Error(`Failed to check if process exists on port ${port}`); 240 | } 241 | }); 242 | } 243 | } 244 | // Step 2: Wrap the invocation logic in an exported function 245 | function runPortClient(ports_1) { 246 | return __awaiter(this, arguments, void 0, function* (ports, options = {}) { 247 | const portClient = new PortClient(ports, options); 248 | return portClient.execute(); 249 | }); 250 | } 251 | module.exports = runPortClient; 252 | -------------------------------------------------------------------------------- /docs/PortClient.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Class: PortClient 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Class: PortClient

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

PortClient(ports, options)

32 | 33 |
A class to manage port operations (kill, check, or verify existence).
34 | 35 | 36 |
37 | 38 |
39 |
40 | 41 | 42 | 43 | 44 |

Constructor

45 | 46 | 47 | 48 |

new PortClient(ports, options)

49 | 50 | 51 | 52 | 53 | 54 | 55 |
56 | Creates an instance of PortClient 57 |
58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 |
Parameters:
68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 |
NameTypeDescription
ports 96 | 97 | 98 | string 99 | | 100 | 101 | number 102 | | 103 | 104 | Array.<number> 105 | 106 | 107 | 108 | Ports to be checked or killed.
options 125 | 126 | 127 | Object 128 | 129 | 130 | 131 | Options for the operation.
143 | 144 | 145 | 146 | 147 | 148 | 149 |
150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 |
Source:
177 |
180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 |
188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 |
210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 |

Methods

227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 |

buildBaseCommand(method, port) → {string}

235 | 236 | 237 | 238 | 239 | 240 | 241 |
242 | Builds the base command for listing the process associated with a port and method. 243 |
244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 |
Parameters:
254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 |
NameTypeDescription
method 282 | 283 | 284 | string 285 | 286 | 287 | 288 | The method (protocol) for the command (e.g., 'tcp' or 'udp').
port 305 | 306 | 307 | number 308 | 309 | 310 | 311 | The port number where the process is running.
323 | 324 | 325 | 326 | 327 | 328 | 329 |
330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 |
Source:
357 |
360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 |
368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 |
Returns:
384 | 385 | 386 |
387 | The base command to find the process ID (PID) of the process running on the specified port and protocol. 388 |
389 | 390 | 391 | 392 |
393 |
394 | Type 395 |
396 |
397 | 398 | string 399 | 400 | 401 |
402 |
403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 |

(async) checkIfProcessExists(port) → {Promise.<boolean>}

417 | 418 | 419 | 420 | 421 | 422 | 423 |
424 | Checks if a process is running on the specified port by using either a fast or normal check based on the current speed setting. 425 |
426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 |
Parameters:
436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 |
NameTypeDescription
port 464 | 465 | 466 | number 467 | 468 | 469 | 470 | The port number where the process is running.
482 | 483 | 484 | 485 | 486 | 487 | 488 |
489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 |
Source:
516 |
519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 |
527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 |
Returns:
543 | 544 | 545 |
546 | A boolean indicating whether a process is running on the specified port. 547 |
548 | 549 | 550 | 551 |
552 |
553 | Type 554 |
555 |
556 | 557 | Promise.<boolean> 558 | 559 | 560 |
561 |
562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 |

(async) checkPortStatus(port) → {Promise.<boolean>}

576 | 577 | 578 | 579 | 580 | 581 | 582 |
583 | Checks whether a given port is active based on the current speed setting. 584 |
585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 |
Parameters:
595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 |
NameTypeDescription
port 623 | 624 | 625 | number 626 | 627 | 628 | 629 | The port number to check.
641 | 642 | 643 | 644 | 645 | 646 | 647 |
648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 |
Source:
675 |
678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 |
686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 |
Returns:
702 | 703 | 704 |
705 | A promise that resolves to a boolean indicating whether the port is active. 706 |
707 | 708 | 709 | 710 |
711 |
712 | Type 713 |
714 |
715 | 716 | Promise.<boolean> 717 | 718 | 719 |
720 |
721 | 722 | 723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 |

error(message) → {void}

735 | 736 | 737 | 738 | 739 | 740 | 741 |
742 | Logs an error message in red. 743 |
744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 |
Parameters:
754 | 755 | 756 | 757 | 758 | 759 | 760 | 761 | 762 | 763 | 764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 | 789 | 790 | 791 | 792 | 793 | 794 | 795 | 796 | 797 | 798 | 799 |
NameTypeDescription
message 782 | 783 | 784 | string 785 | 786 | 787 | 788 | The error message to log.
800 | 801 | 802 | 803 | 804 | 805 | 806 |
807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 | 815 | 816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 | 824 | 825 | 826 | 827 | 828 | 829 | 830 | 831 | 832 | 833 |
Source:
834 |
837 | 838 | 839 | 840 | 841 | 842 | 843 | 844 |
845 | 846 | 847 | 848 | 849 | 850 | 851 | 852 | 853 | 854 | 855 | 856 | 857 | 858 | 859 | 860 |
Returns:
861 | 862 | 863 | 864 | 865 |
866 |
867 | Type 868 |
869 |
870 | 871 | void 872 | 873 | 874 |
875 |
876 | 877 | 878 | 879 | 880 | 881 | 882 | 883 | 884 | 885 | 886 | 887 | 888 | 889 |

(async) execute() → {Promise.<void>}

890 | 891 | 892 | 893 | 894 | 895 | 896 |
897 | Executes the port operation based on the action flag. 898 |
899 | 900 | 901 | 902 | 903 | 904 | 905 | 906 | 907 | 908 | 909 | 910 | 911 | 912 |
913 | 914 | 915 | 916 | 917 | 918 | 919 | 920 | 921 | 922 | 923 | 924 | 925 | 926 | 927 | 928 | 929 | 930 | 931 | 932 | 933 | 934 | 935 | 936 | 937 | 938 | 939 |
Source:
940 |
943 | 944 | 945 | 946 | 947 | 948 | 949 | 950 |
951 | 952 | 953 | 954 | 955 | 956 | 957 | 958 | 959 | 960 | 961 | 962 | 963 | 964 | 965 | 966 |
Returns:
967 | 968 | 969 | 970 | 971 |
972 |
973 | Type 974 |
975 |
976 | 977 | Promise.<void> 978 | 979 | 980 |
981 |
982 | 983 | 984 | 985 | 986 | 987 | 988 | 989 | 990 | 991 | 992 | 993 | 994 | 995 |

(async) getUnixKillCommand(port, methodopt, gracefulopt) → {Promise.<string>}

996 | 997 | 998 | 999 | 1000 | 1001 | 1002 |
1003 | Constructs the Unix command to kill a process running on a specified port. 1004 | The command will either gracefully or forcefully terminate the process, depending on the `graceful` parameter. 1005 |
1006 | 1007 | 1008 | 1009 | 1010 | 1011 | 1012 | 1013 | 1014 | 1015 |
Parameters:
1016 | 1017 | 1018 | 1019 | 1020 | 1021 | 1022 | 1023 | 1024 | 1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | 1032 | 1033 | 1034 | 1035 | 1036 | 1037 | 1038 | 1039 | 1040 | 1041 | 1042 | 1043 | 1044 | 1045 | 1046 | 1047 | 1055 | 1056 | 1057 | 1064 | 1065 | 1066 | 1067 | 1070 | 1071 | 1072 | 1073 | 1074 | 1075 | 1076 | 1077 | 1078 | 1079 | 1080 | 1081 | 1082 | 1090 | 1091 | 1092 | 1101 | 1102 | 1103 | 1104 | 1109 | 1110 | 1111 | 1112 | 1113 | 1114 | 1115 | 1116 | 1117 | 1118 | 1119 | 1120 | 1121 | 1129 | 1130 | 1131 | 1140 | 1141 | 1142 | 1143 | 1148 | 1149 | 1150 | 1151 | 1152 | 1153 | 1154 | 1155 |
NameTypeAttributesDefaultDescription
port 1048 | 1049 | 1050 | number 1051 | 1052 | 1053 | 1054 | 1058 | 1059 | 1060 | 1061 | 1062 | 1063 | 1068 | 1069 | The port number where the process is running.
method 1083 | 1084 | 1085 | string 1086 | 1087 | 1088 | 1089 | 1093 | 1094 | <optional>
1095 | 1096 | 1097 | 1098 | 1099 | 1100 |
1105 | 1106 | 'tcp' 1107 | 1108 | The method (protocol) for the command (e.g., 'tcp' or 'udp'). Defaults to 'tcp'.
graceful 1122 | 1123 | 1124 | boolean 1125 | 1126 | 1127 | 1128 | 1132 | 1133 | <optional>
1134 | 1135 | 1136 | 1137 | 1138 | 1139 |
1144 | 1145 | false 1146 | 1147 | Whether to send a graceful kill signal (`true`) or a forceful one (`false`). Defaults to `false` (forceful kill).
1156 | 1157 | 1158 | 1159 | 1160 | 1161 | 1162 |
1163 | 1164 | 1165 | 1166 | 1167 | 1168 | 1169 | 1170 | 1171 | 1172 | 1173 | 1174 | 1175 | 1176 | 1177 | 1178 | 1179 | 1180 | 1181 | 1182 | 1183 | 1184 | 1185 | 1186 | 1187 | 1188 | 1189 |
Source:
1190 |
1193 | 1194 | 1195 | 1196 | 1197 | 1198 | 1199 | 1200 |
1201 | 1202 | 1203 | 1204 | 1205 | 1206 | 1207 | 1208 | 1209 | 1210 | 1211 | 1212 | 1213 | 1214 |
Throws:
1215 | 1216 | 1217 | 1218 |
1219 |
1220 |
1221 | Throws an error if no process is found running on the specified port. 1222 |
1223 |
1224 |
1225 |
1226 |
1227 |
1228 | Type 1229 |
1230 |
1231 | 1232 | Error 1233 | 1234 | 1235 |
1236 |
1237 |
1238 |
1239 |
1240 | 1241 | 1242 | 1243 | 1244 | 1245 |
Returns:
1246 | 1247 | 1248 |
1249 | The full Unix command string to kill the process. 1250 |
1251 | 1252 | 1253 | 1254 |
1255 |
1256 | Type 1257 |
1258 |
1259 | 1260 | Promise.<string> 1261 | 1262 | 1263 |
1264 |
1265 | 1266 | 1267 | 1268 | 1269 | 1270 | 1271 | 1272 | 1273 | 1274 | 1275 | 1276 | 1277 | 1278 |

(async) getWindowsKillCommand(port) → {string}

1279 | 1280 | 1281 | 1282 | 1283 | 1284 | 1285 |
1286 | Gets the Windows command to kill a port. 1287 |
1288 | 1289 | 1290 | 1291 | 1292 | 1293 | 1294 | 1295 | 1296 | 1297 |
Parameters:
1298 | 1299 | 1300 | 1301 | 1302 | 1303 | 1304 | 1305 | 1306 | 1307 | 1308 | 1309 | 1310 | 1311 | 1312 | 1313 | 1314 | 1315 | 1316 | 1317 | 1318 | 1319 | 1320 | 1321 | 1322 | 1323 | 1324 | 1325 | 1333 | 1334 | 1335 | 1336 | 1337 | 1338 | 1339 | 1340 | 1341 | 1342 | 1343 |
NameTypeDescription
port 1326 | 1327 | 1328 | number 1329 | 1330 | 1331 | 1332 | The port to kill.
1344 | 1345 | 1346 | 1347 | 1348 | 1349 | 1350 |
1351 | 1352 | 1353 | 1354 | 1355 | 1356 | 1357 | 1358 | 1359 | 1360 | 1361 | 1362 | 1363 | 1364 | 1365 | 1366 | 1367 | 1368 | 1369 | 1370 | 1371 | 1372 | 1373 | 1374 | 1375 | 1376 | 1377 |
Source:
1378 |
1381 | 1382 | 1383 | 1384 | 1385 | 1386 | 1387 | 1388 |
1389 | 1390 | 1391 | 1392 | 1393 | 1394 | 1395 | 1396 | 1397 | 1398 | 1399 | 1400 | 1401 | 1402 | 1403 | 1404 |
Returns:
1405 | 1406 | 1407 |
1408 | The Windows kill command. 1409 |
1410 | 1411 | 1412 | 1413 |
1414 |
1415 | Type 1416 |
1417 |
1418 | 1419 | string 1420 | 1421 | 1422 |
1423 |
1424 | 1425 | 1426 | 1427 | 1428 | 1429 | 1430 | 1431 | 1432 | 1433 | 1434 | 1435 | 1436 | 1437 |

(async) handlePorts(ports) → {Promise}

1438 | 1439 | 1440 | 1441 | 1442 | 1443 | 1444 |
1445 | Handles the action on a list of ports based on the specified action type. 1446 |
1447 | 1448 | 1449 | 1450 | 1451 | 1452 | 1453 | 1454 | 1455 | 1456 |
Parameters:
1457 | 1458 | 1459 | 1460 | 1461 | 1462 | 1463 | 1464 | 1465 | 1466 | 1467 | 1468 | 1469 | 1470 | 1471 | 1472 | 1473 | 1474 | 1475 | 1476 | 1477 | 1478 | 1479 | 1480 | 1481 | 1482 | 1483 | 1484 | 1492 | 1493 | 1494 | 1495 | 1496 | 1497 | 1498 | 1499 | 1500 | 1501 | 1502 |
NameTypeDescription
ports 1485 | 1486 | 1487 | Array.<number> 1488 | 1489 | 1490 | 1491 | The list of port numbers to act upon.
1503 | 1504 | 1505 | 1506 | 1507 | 1508 | 1509 |
1510 | 1511 | 1512 | 1513 | 1514 | 1515 | 1516 | 1517 | 1518 | 1519 | 1520 | 1521 | 1522 | 1523 | 1524 | 1525 | 1526 | 1527 | 1528 | 1529 | 1530 | 1531 | 1532 | 1533 | 1534 | 1535 | 1536 |
Source:
1537 |
1540 | 1541 | 1542 | 1543 | 1544 | 1545 | 1546 | 1547 |
1548 | 1549 | 1550 | 1551 | 1552 | 1553 | 1554 | 1555 | 1556 | 1557 | 1558 | 1559 | 1560 | 1561 | 1562 | 1563 |
Returns:
1564 | 1565 | 1566 |
1567 | The result of the action performed. 1568 |
1569 | 1570 | 1571 | 1572 |
1573 |
1574 | Type 1575 |
1576 |
1577 | 1578 | Promise 1579 | 1580 | 1581 |
1582 |
1583 | 1584 | 1585 | 1586 | 1587 | 1588 | 1589 | 1590 | 1591 | 1592 | 1593 | 1594 | 1595 | 1596 |

(async) killPorts(ports) → {Promise.<void>}

1597 | 1598 | 1599 | 1600 | 1601 | 1602 | 1603 |
1604 | Kills the specified ports. 1605 |
1606 | 1607 | 1608 | 1609 | 1610 | 1611 | 1612 | 1613 | 1614 | 1615 |
Parameters:
1616 | 1617 | 1618 | 1619 | 1620 | 1621 | 1622 | 1623 | 1624 | 1625 | 1626 | 1627 | 1628 | 1629 | 1630 | 1631 | 1632 | 1633 | 1634 | 1635 | 1636 | 1637 | 1638 | 1639 | 1640 | 1641 | 1642 | 1643 | 1651 | 1652 | 1653 | 1654 | 1655 | 1656 | 1657 | 1658 | 1659 | 1660 | 1661 |
NameTypeDescription
ports 1644 | 1645 | 1646 | Array.<number> 1647 | 1648 | 1649 | 1650 | The ports to kill.
1662 | 1663 | 1664 | 1665 | 1666 | 1667 | 1668 |
1669 | 1670 | 1671 | 1672 | 1673 | 1674 | 1675 | 1676 | 1677 | 1678 | 1679 | 1680 | 1681 | 1682 | 1683 | 1684 | 1685 | 1686 | 1687 | 1688 | 1689 | 1690 | 1691 | 1692 | 1693 | 1694 | 1695 |
Source:
1696 |
1699 | 1700 | 1701 | 1702 | 1703 | 1704 | 1705 | 1706 |
1707 | 1708 | 1709 | 1710 | 1711 | 1712 | 1713 | 1714 | 1715 | 1716 | 1717 | 1718 | 1719 | 1720 | 1721 | 1722 |
Returns:
1723 | 1724 | 1725 | 1726 | 1727 |
1728 |
1729 | Type 1730 |
1731 |
1732 | 1733 | Promise.<void> 1734 | 1735 | 1736 |
1737 |
1738 | 1739 | 1740 | 1741 | 1742 | 1743 | 1744 | 1745 | 1746 | 1747 | 1748 | 1749 | 1750 | 1751 |

(async) listActivePorts() → {Promise.<Array.<string>>}

1752 | 1753 | 1754 | 1755 | 1756 | 1757 | 1758 |
1759 | Lists active ports based on the platform and speed flag. 1760 |
1761 | 1762 | 1763 | 1764 | 1765 | 1766 | 1767 | 1768 | 1769 | 1770 | 1771 | 1772 | 1773 | 1774 |
1775 | 1776 | 1777 | 1778 | 1779 | 1780 | 1781 | 1782 | 1783 | 1784 | 1785 | 1786 | 1787 | 1788 | 1789 | 1790 | 1791 | 1792 | 1793 | 1794 | 1795 | 1796 | 1797 | 1798 | 1799 | 1800 | 1801 |
Source:
1802 |
1805 | 1806 | 1807 | 1808 | 1809 | 1810 | 1811 | 1812 |
1813 | 1814 | 1815 | 1816 | 1817 | 1818 | 1819 | 1820 | 1821 | 1822 | 1823 | 1824 | 1825 | 1826 | 1827 | 1828 |
Returns:
1829 | 1830 | 1831 |
1832 | List of active ports. 1833 |
1834 | 1835 | 1836 | 1837 |
1838 |
1839 | Type 1840 |
1841 |
1842 | 1843 | Promise.<Array.<string>> 1844 | 1845 | 1846 |
1847 |
1848 | 1849 | 1850 | 1851 | 1852 | 1853 | 1854 | 1855 | 1856 | 1857 | 1858 | 1859 | 1860 | 1861 |

log(message)

1862 | 1863 | 1864 | 1865 | 1866 | 1867 | 1868 |
1869 | Logs messages if verbose mode is enabled. 1870 |
1871 | 1872 | 1873 | 1874 | 1875 | 1876 | 1877 | 1878 | 1879 | 1880 |
Parameters:
1881 | 1882 | 1883 | 1884 | 1885 | 1886 | 1887 | 1888 | 1889 | 1890 | 1891 | 1892 | 1893 | 1894 | 1895 | 1896 | 1897 | 1898 | 1899 | 1900 | 1901 | 1902 | 1903 | 1904 | 1905 | 1906 | 1907 | 1908 | 1916 | 1917 | 1918 | 1919 | 1920 | 1921 | 1922 | 1923 | 1924 | 1925 | 1926 |
NameTypeDescription
message 1909 | 1910 | 1911 | string 1912 | 1913 | 1914 | 1915 | The message to log.
1927 | 1928 | 1929 | 1930 | 1931 | 1932 | 1933 |
1934 | 1935 | 1936 | 1937 | 1938 | 1939 | 1940 | 1941 | 1942 | 1943 | 1944 | 1945 | 1946 | 1947 | 1948 | 1949 | 1950 | 1951 | 1952 | 1953 | 1954 | 1955 | 1956 | 1957 | 1958 | 1959 | 1960 |
Source:
1961 |
1964 | 1965 | 1966 | 1967 | 1968 | 1969 | 1970 | 1971 |
1972 | 1973 | 1974 | 1975 | 1976 | 1977 | 1978 | 1979 | 1980 | 1981 | 1982 | 1983 | 1984 | 1985 | 1986 | 1987 | 1988 | 1989 | 1990 | 1991 | 1992 | 1993 | 1994 | 1995 | 1996 | 1997 | 1998 |

parsePorts() → {Array.<number>}

1999 | 2000 | 2001 | 2002 | 2003 | 2004 | 2005 |
2006 | Parses the provided ports into an array of valid ports. 2007 |
2008 | 2009 | 2010 | 2011 | 2012 | 2013 | 2014 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 |
2022 | 2023 | 2024 | 2025 | 2026 | 2027 | 2028 | 2029 | 2030 | 2031 | 2032 | 2033 | 2034 | 2035 | 2036 | 2037 | 2038 | 2039 | 2040 | 2041 | 2042 | 2043 | 2044 | 2045 | 2046 | 2047 | 2048 |
Source:
2049 |
2052 | 2053 | 2054 | 2055 | 2056 | 2057 | 2058 | 2059 |
2060 | 2061 | 2062 | 2063 | 2064 | 2065 | 2066 | 2067 | 2068 | 2069 | 2070 | 2071 | 2072 | 2073 | 2074 | 2075 |
Returns:
2076 | 2077 | 2078 |
2079 | The parsed ports. 2080 |
2081 | 2082 | 2083 | 2084 |
2085 |
2086 | Type 2087 |
2088 |
2089 | 2090 | Array.<number> 2091 | 2092 | 2093 |
2094 |
2095 | 2096 | 2097 | 2098 | 2099 | 2100 | 2101 | 2102 | 2103 | 2104 | 2105 | 2106 | 2107 | 2108 |

parseUnixPorts(lines) → {Array.<string>}

2109 | 2110 | 2111 | 2112 | 2113 | 2114 | 2115 |
2116 | Parses active ports for Unix-like systems. 2117 |
2118 | 2119 | 2120 | 2121 | 2122 | 2123 | 2124 | 2125 | 2126 | 2127 |
Parameters:
2128 | 2129 | 2130 | 2131 | 2132 | 2133 | 2134 | 2135 | 2136 | 2137 | 2138 | 2139 | 2140 | 2141 | 2142 | 2143 | 2144 | 2145 | 2146 | 2147 | 2148 | 2149 | 2150 | 2151 | 2152 | 2153 | 2154 | 2155 | 2163 | 2164 | 2165 | 2166 | 2167 | 2168 | 2169 | 2170 | 2171 | 2172 | 2173 |
NameTypeDescription
lines 2156 | 2157 | 2158 | Array.<string> 2159 | 2160 | 2161 | 2162 | The output lines from the lsof command.
2174 | 2175 | 2176 | 2177 | 2178 | 2179 | 2180 |
2181 | 2182 | 2183 | 2184 | 2185 | 2186 | 2187 | 2188 | 2189 | 2190 | 2191 | 2192 | 2193 | 2194 | 2195 | 2196 | 2197 | 2198 | 2199 | 2200 | 2201 | 2202 | 2203 | 2204 | 2205 | 2206 | 2207 |
Source:
2208 |
2211 | 2212 | 2213 | 2214 | 2215 | 2216 | 2217 | 2218 |
2219 | 2220 | 2221 | 2222 | 2223 | 2224 | 2225 | 2226 | 2227 | 2228 | 2229 | 2230 | 2231 | 2232 | 2233 | 2234 |
Returns:
2235 | 2236 | 2237 |
2238 | The parsed active ports. 2239 |
2240 | 2241 | 2242 | 2243 |
2244 |
2245 | Type 2246 |
2247 |
2248 | 2249 | Array.<string> 2250 | 2251 | 2252 |
2253 |
2254 | 2255 | 2256 | 2257 | 2258 | 2259 | 2260 | 2261 | 2262 | 2263 | 2264 | 2265 | 2266 | 2267 |

parseWindowsPorts(lines) → {Array.<string>}

2268 | 2269 | 2270 | 2271 | 2272 | 2273 | 2274 |
2275 | Parses active ports for Windows. 2276 |
2277 | 2278 | 2279 | 2280 | 2281 | 2282 | 2283 | 2284 | 2285 | 2286 |
Parameters:
2287 | 2288 | 2289 | 2290 | 2291 | 2292 | 2293 | 2294 | 2295 | 2296 | 2297 | 2298 | 2299 | 2300 | 2301 | 2302 | 2303 | 2304 | 2305 | 2306 | 2307 | 2308 | 2309 | 2310 | 2311 | 2312 | 2313 | 2314 | 2322 | 2323 | 2324 | 2325 | 2326 | 2327 | 2328 | 2329 | 2330 | 2331 | 2332 |
NameTypeDescription
lines 2315 | 2316 | 2317 | Array.<string> 2318 | 2319 | 2320 | 2321 | The output lines from the netstat command.
2333 | 2334 | 2335 | 2336 | 2337 | 2338 | 2339 |
2340 | 2341 | 2342 | 2343 | 2344 | 2345 | 2346 | 2347 | 2348 | 2349 | 2350 | 2351 | 2352 | 2353 | 2354 | 2355 | 2356 | 2357 | 2358 | 2359 | 2360 | 2361 | 2362 | 2363 | 2364 | 2365 | 2366 |
Source:
2367 |
2370 | 2371 | 2372 | 2373 | 2374 | 2375 | 2376 | 2377 |
2378 | 2379 | 2380 | 2381 | 2382 | 2383 | 2384 | 2385 | 2386 | 2387 | 2388 | 2389 | 2390 | 2391 | 2392 | 2393 |
Returns:
2394 | 2395 | 2396 |
2397 | The parsed active ports. 2398 |
2399 | 2400 | 2401 | 2402 |
2403 |
2404 | Type 2405 |
2406 |
2407 | 2408 | Array.<string> 2409 | 2410 | 2411 |
2412 |
2413 | 2414 | 2415 | 2416 | 2417 | 2418 | 2419 | 2420 | 2421 | 2422 | 2423 | 2424 | 2425 | 2426 |

promptUserToSelectPorts(activePorts) → {Promise.<Array.<number>>}

2427 | 2428 | 2429 | 2430 | 2431 | 2432 | 2433 |
2434 | Prompts the user to select ports interactively. 2435 |
2436 | 2437 | 2438 | 2439 | 2440 | 2441 | 2442 | 2443 | 2444 | 2445 |
Parameters:
2446 | 2447 | 2448 | 2449 | 2450 | 2451 | 2452 | 2453 | 2454 | 2455 | 2456 | 2457 | 2458 | 2459 | 2460 | 2461 | 2462 | 2463 | 2464 | 2465 | 2466 | 2467 | 2468 | 2469 | 2470 | 2471 | 2472 | 2473 | 2481 | 2482 | 2483 | 2484 | 2485 | 2486 | 2487 | 2488 | 2489 | 2490 | 2491 |
NameTypeDescription
activePorts 2474 | 2475 | 2476 | Array.<string> 2477 | 2478 | 2479 | 2480 | List of active ports to choose from.
2492 | 2493 | 2494 | 2495 | 2496 | 2497 | 2498 |
2499 | 2500 | 2501 | 2502 | 2503 | 2504 | 2505 | 2506 | 2507 | 2508 | 2509 | 2510 | 2511 | 2512 | 2513 | 2514 | 2515 | 2516 | 2517 | 2518 | 2519 | 2520 | 2521 | 2522 | 2523 | 2524 | 2525 |
Source:
2526 |
2529 | 2530 | 2531 | 2532 | 2533 | 2534 | 2535 | 2536 |
2537 | 2538 | 2539 | 2540 | 2541 | 2542 | 2543 | 2544 | 2545 | 2546 | 2547 | 2548 | 2549 | 2550 | 2551 | 2552 |
Returns:
2553 | 2554 | 2555 |
2556 | The selected ports. 2557 |
2558 | 2559 | 2560 | 2561 |
2562 |
2563 | Type 2564 |
2565 |
2566 | 2567 | Promise.<Array.<number>> 2568 | 2569 | 2570 |
2571 |
2572 | 2573 | 2574 | 2575 | 2576 | 2577 | 2578 | 2579 | 2580 | 2581 | 2582 | 2583 | 2584 | 2585 |

(async) showPortInfo(ports)

2586 | 2587 | 2588 | 2589 | 2590 | 2591 | 2592 |
2593 | Checks and logs the status of each port, indicating whether it is active or not. 2594 |
2595 | 2596 | 2597 | 2598 | 2599 | 2600 | 2601 | 2602 | 2603 | 2604 |
Parameters:
2605 | 2606 | 2607 | 2608 | 2609 | 2610 | 2611 | 2612 | 2613 | 2614 | 2615 | 2616 | 2617 | 2618 | 2619 | 2620 | 2621 | 2622 | 2623 | 2624 | 2625 | 2626 | 2627 | 2628 | 2629 | 2630 | 2631 | 2632 | 2640 | 2641 | 2642 | 2643 | 2644 | 2645 | 2646 | 2647 | 2648 | 2649 | 2650 |
NameTypeDescription
ports 2633 | 2634 | 2635 | Array.<number> 2636 | 2637 | 2638 | 2639 | An array of port numbers to check for activity.
2651 | 2652 | 2653 | 2654 | 2655 | 2656 | 2657 |
2658 | 2659 | 2660 | 2661 | 2662 | 2663 | 2664 | 2665 | 2666 | 2667 | 2668 | 2669 | 2670 | 2671 | 2672 | 2673 | 2674 | 2675 | 2676 | 2677 | 2678 | 2679 | 2680 | 2681 | 2682 | 2683 | 2684 |
Source:
2685 |
2688 | 2689 | 2690 | 2691 | 2692 | 2693 | 2694 | 2695 |
2696 | 2697 | 2698 | 2699 | 2700 | 2701 | 2702 | 2703 | 2704 | 2705 | 2706 | 2707 | 2708 | 2709 | 2710 | 2711 | 2712 | 2713 | 2714 | 2715 | 2716 | 2717 | 2718 | 2719 | 2720 | 2721 | 2722 |

success(message) → {void}

2723 | 2724 | 2725 | 2726 | 2727 | 2728 | 2729 |
2730 | Logs a success message in green. 2731 |
2732 | 2733 | 2734 | 2735 | 2736 | 2737 | 2738 | 2739 | 2740 | 2741 |
Parameters:
2742 | 2743 | 2744 | 2745 | 2746 | 2747 | 2748 | 2749 | 2750 | 2751 | 2752 | 2753 | 2754 | 2755 | 2756 | 2757 | 2758 | 2759 | 2760 | 2761 | 2762 | 2763 | 2764 | 2765 | 2766 | 2767 | 2768 | 2769 | 2777 | 2778 | 2779 | 2780 | 2781 | 2782 | 2783 | 2784 | 2785 | 2786 | 2787 |
NameTypeDescription
message 2770 | 2771 | 2772 | string 2773 | 2774 | 2775 | 2776 | The success message to log.
2788 | 2789 | 2790 | 2791 | 2792 | 2793 | 2794 |
2795 | 2796 | 2797 | 2798 | 2799 | 2800 | 2801 | 2802 | 2803 | 2804 | 2805 | 2806 | 2807 | 2808 | 2809 | 2810 | 2811 | 2812 | 2813 | 2814 | 2815 | 2816 | 2817 | 2818 | 2819 | 2820 | 2821 |
Source:
2822 |
2825 | 2826 | 2827 | 2828 | 2829 | 2830 | 2831 | 2832 |
2833 | 2834 | 2835 | 2836 | 2837 | 2838 | 2839 | 2840 | 2841 | 2842 | 2843 | 2844 | 2845 | 2846 | 2847 | 2848 |
Returns:
2849 | 2850 | 2851 | 2852 | 2853 |
2854 |
2855 | Type 2856 |
2857 |
2858 | 2859 | void 2860 | 2861 | 2862 |
2863 |
2864 | 2865 | 2866 | 2867 | 2868 | 2869 | 2870 | 2871 | 2872 | 2873 | 2874 | 2875 | 2876 | 2877 |
2878 | 2879 |
2880 | 2881 | 2882 | 2883 | 2884 |
2885 | 2886 | 2889 | 2890 |
2891 | 2892 | 2895 | 2896 | 2897 | 2898 | 2899 | -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-Bold-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-Bold-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-BoldItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-BoldItalic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-Italic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-Italic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-Light-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-Light-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-LightItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-LightItalic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-Regular-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/docs/fonts/OpenSans-Regular-webfont.woff -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Home 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Home

21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |

30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 |
51 | 52 | 55 | 56 |
57 | 58 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /docs/index.js.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Source: index.js 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Source: index.js

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 |
29 |
'use strict';
 30 | 
 31 | const sh = require('shell-exec');
 32 | const readline = require('readline')
 33 | 
 34 | /**
 35 |  * A class to manage port operations (kill, check, or verify existence).
 36 |  */
 37 | class PortClient {
 38 |   /**
 39 |    * Creates an instance of PortClient
 40 |    * @param {string | number | number[]} ports - Ports to be checked or killed.
 41 |    * @param {Object} options - Options for the operation.
 42 |    */
 43 |   constructor(ports, {
 44 |     method = 'tcp',
 45 |     action = 'check',
 46 |     interactive = false,
 47 |     dryRun = false,
 48 |     verbose = false,
 49 |     graceful = false,
 50 |     filter = null,
 51 |     range = null,
 52 |     speed = 'safe',
 53 |   } = {}) {
 54 |     this.ports = ports;
 55 |     this.method = method;
 56 |     this.action = action;
 57 |     this.interactive = interactive;
 58 |     this.dryRun = dryRun;
 59 |     this.verbose = verbose;
 60 |     this.graceful = graceful;
 61 |     this.filter = filter;
 62 |     this.range = range;
 63 |     this.speed = speed; 
 64 |     this.platform = process.platform;
 65 |   }
 66 | 
 67 |   /**
 68 |    * Logs messages if verbose mode is enabled.
 69 |    * @param {string} message - The message to log.
 70 |    */
 71 |   log(message) {
 72 |     if (this.verbose) {
 73 |       console.log(message);
 74 |     }
 75 |   }
 76 | 
 77 |   /**
 78 |    * Parses the provided ports into an array of valid ports.
 79 |    * @returns {number[]} The parsed ports.
 80 |    */
 81 |   parsePorts() {
 82 |     if (Array.isArray(this.ports)) {
 83 |       return this.ports.map(Number).filter(Boolean);
 84 |     } else if (this.range) {
 85 |       const [start, end] = this.range.split('-').map(Number);
 86 |       return Array.from({ length: end - start + 1 }, (_, i) => start + i);
 87 |     } else {
 88 |       const port = Number(this.ports);
 89 |       return port ? [port] : [];
 90 |     }
 91 |   }
 92 | 
 93 |   /**
 94 |    * Executes the port operation based on the action flag.
 95 |    * @returns {Promise<void>}
 96 |    */
 97 |   async execute() {
 98 |     const parsedPorts = this.parsePorts();
 99 |     if (parsedPorts.length === 0) {
100 |       throw new Error('Invalid or no port(s) provided.');
101 |     }
102 | 
103 |     if (this.dryRun) {
104 |       this.success(`Dry run: Ports to operate on - ${parsedPorts.join(', ')}`);
105 |       return;
106 |     }
107 | 
108 |     if (this.interactive) {
109 |       const activePorts = await this.listActivePorts();
110 |       const selectedPorts = await this.promptUserToSelectPorts(activePorts);
111 |       return this.handlePorts(selectedPorts);
112 |     }
113 | 
114 |     return this.handlePorts(parsedPorts);
115 |   }
116 | 
117 |   /**
118 |    * Lists active ports based on the platform and speed flag.
119 |    * @returns {Promise<string[]>} List of active ports.
120 |    */
121 |   async listActivePorts() {
122 |     const command = this.platform === 'win32' 
123 |       ? 'netstat -nao' 
124 |       : (this.speed === 'fast' 
125 |         ? `lsof -i :${this.ports}`  
126 |         : 'lsof -i -P -n');  
127 | 
128 |     try {
129 |       const { stdout } = await sh(command);
130 |       const lines = stdout.split('\n');
131 |       return this.platform === 'win32' ? this.parseWindowsPorts(lines) : this.parseUnixPorts(lines);
132 |     } catch (error) {
133 |       throw new Error(`Failed to list active ports: ${error.message}`);
134 |     }
135 |   }
136 | 
137 |   /**
138 |    * Parses active ports for Windows.
139 |    * @param {string[]} lines - The output lines from the netstat command.
140 |    * @returns {string[]} The parsed active ports.
141 |    */
142 |   parseWindowsPorts(lines) {
143 |     const regex = new RegExp(`^ *${this.method.toUpperCase()} *[^ ]*:(\\d+),`, 'gm');
144 |     return lines.reduce((acc, line) => {
145 |       const match = line.match(regex);
146 |       if (match && match[1] && !acc.includes(match[1])) {
147 |         acc.push(match[1]);
148 |       }
149 |       return acc;
150 |     }, []);
151 |   }
152 | 
153 |   /**
154 |    * Parses active ports for Unix-like systems.
155 |    * @param {string[]} lines - The output lines from the lsof command.
156 |    * @returns {string[]} The parsed active ports.
157 |    */
158 |   parseUnixPorts(lines) {
159 | 
160 |     const regex = /(?<=:\d{1,5})->|\b\d{1,5}(?=->|\s+\(CLOSED\)|\s+\(ESTABLISHED\)|\s+\(LISTEN\))/g;
161 | 
162 |     return lines.flatMap(line => line.match(regex)).filter(Boolean);
163 | 
164 |   }
165 | 
166 |   /**
167 |    * Prompts the user to select ports interactively.
168 |    * @param {string[]} activePorts - List of active ports to choose from.
169 |    * @returns {Promise<number[]>} The selected ports.
170 |    */
171 |   promptUserToSelectPorts(activePorts) {
172 |     return new Promise((resolve) => {
173 |       const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
174 | 
175 |       activePorts.forEach((port, index) => {
176 |         this.success(`${index + 1}. ${port}`);
177 |       });
178 | 
179 |       rl.question('Select ports to operate on (comma-separated indices): ', (answer) => {
180 |         const indices = answer.split(',').map(Number);
181 |         const selectedPorts = indices.map((index) => activePorts[index - 1]).filter(Boolean);
182 |         rl.close();
183 |         resolve(selectedPorts);
184 |       });
185 |     });
186 |   }
187 | 
188 |   /**
189 |    * Handles the action on a list of ports based on the specified action type.
190 |    * 
191 |    * @param {number[]} ports - The list of port numbers to act upon.
192 |    * @returns {Promise} The result of the action performed.
193 |    */
194 |   async handlePorts(ports) {
195 |     switch (this.action) {
196 |       case 'check':
197 |       case 'isExist':
198 |         return this.showPortInfo(ports);
199 | 
200 |       case 'kill':
201 |         return this.killPorts(ports);
202 | 
203 |       default:
204 |         throw new Error(`Unknown action: ${this.action}`);
205 |     }
206 |   }
207 | 
208 |   async isExistFast(port) {
209 |     const { stdout } = await sh(`lsof -i :${port}`);
210 | 
211 |     return stdout.includes('LISTEN');
212 |   }
213 | 
214 |   async isExistNormal(port) {
215 |     const activePorts = await this.listActivePorts();
216 | 
217 |     return activePorts.includes(String(port));
218 |   }
219 | 
220 |   /**
221 |    * Logs a success message in green.
222 |    * 
223 |    * @param {string} message - The success message to log.
224 |    * @returns {void}
225 |    */
226 |   success(message) {
227 |     console.log('\x1b[32m%s\x1b[0m', `${message}`);
228 |   }
229 | 
230 |   /**
231 |    * Logs an error message in red.
232 |    * 
233 |    * @param {string} message - The error message to log.
234 |    * @returns {void}
235 |    */
236 |   error(message) {
237 |     console.log('\x1b[31m%s\x1b[0m', `${message}`);
238 |   }
239 | 
240 |   /**
241 |    * Checks and logs the status of each port, indicating whether it is active or not.
242 |    * 
243 |    * @param {number[]} ports - An array of port numbers to check for activity.
244 |    */
245 |   async showPortInfo(ports) {
246 |     for (const port of ports) {
247 |       try {
248 |         const isActive = await this.checkPortStatus(port);
249 | 
250 |         this.success(isActive ? `Port ${port} is active.` : `Port ${port} is not active.`);
251 |       } catch (error) {
252 |         this.error(`Error checking port ${port}: ${error.message}`);
253 |       }
254 |     }
255 |   }
256 | 
257 |   /**
258 |    * Checks whether a given port is active based on the current speed setting.
259 |    * 
260 |    * @param {number} port - The port number to check.
261 |    * @returns {Promise<boolean>} A promise that resolves to a boolean indicating whether the port is active.
262 |    */
263 |   async checkPortStatus(port) {
264 |     const checkMethod = this.speed === 'fast' ? this.isExistFast : this.isExistNormal;
265 |     return await checkMethod.call(this, port);
266 |   }
267 | 
268 |   /**
269 |    * Kills the specified ports.
270 |    * @param {number[]} ports - The ports to kill.
271 |    * @returns {Promise<void>}
272 |    */
273 |   async killPorts(ports) {
274 |     for (const port of ports) {
275 |       try {
276 |         const command = this.platform === 'win32' 
277 |           ? await this.getWindowsKillCommand(port)
278 |           : await this.getUnixKillCommand(port, this.method, this.graceful);
279 | 
280 |         this.log(`Executing: ${command}`);
281 |         const result = await sh(command);
282 |         this.success(`Successfully killed port ${port} ${result.stdout}`);
283 |       } catch (error) {
284 |         this.error(`Failed to kill port ${port}: ${error.message}`);
285 |       }
286 |     }
287 |   }
288 | 
289 |   /**
290 |    * Gets the Windows command to kill a port.
291 |    * @param {number} port - The port to kill.
292 |    * @returns {string} The Windows kill command.
293 |    */
294 |   async getWindowsKillCommand(port) {
295 |     try {
296 |       const { stdout } = await sh('netstat -nao');
297 |       const lines = stdout.split('\n');
298 |       const regex = new RegExp(`^ *${this.method.toUpperCase()} *[^ ]*:${port},`, 'gm');
299 |       const linesWithPort = lines.filter(line => regex.test(line));
300 | 
301 |       const pids = linesWithPort.reduce((acc, line) => {
302 |         const pidMatch = line.match(/(\d+)\w*/);
303 |         if (pidMatch) acc.push(pidMatch[1]);
304 |         return acc;
305 |       }, []);
306 | 
307 |       return `TaskKill /F /PID ${pids.join(' /PID ')}`;
308 |     } catch (error) {
309 |       throw new Error(`Failed to get Windows kill command: ${error.message}`);
310 |     }
311 |   }
312 | 
313 |   /**
314 |    * Constructs the Unix command to kill a process running on a specified port.
315 |    * The command will either gracefully or forcefully terminate the process, depending on the `graceful` parameter.
316 |    *
317 |    * @param {number} port - The port number where the process is running.
318 |    * @param {string} [method='tcp'] - The method (protocol) for the command (e.g., 'tcp' or 'udp'). Defaults to 'tcp'.
319 |    * @param {boolean} [graceful=false] - Whether to send a graceful kill signal (`true`) or a forceful one (`false`). Defaults to `false` (forceful kill).
320 |    * @returns {Promise<string>} The full Unix command string to kill the process.
321 |    * @throws {Error} Throws an error if no process is found running on the specified port.
322 |    */
323 |   async getUnixKillCommand(port, method = 'tcp', graceful = false) {
324 |     const baseCommand = this.buildBaseCommand(method, port);
325 |     const killCommand = graceful ? 'kill' : 'kill -9';
326 | 
327 |     try {
328 |       const processExists = await this.checkIfProcessExists(port);
329 | 
330 |       if (!processExists) {
331 |         throw new Error('No process running on port');
332 |       }
333 | 
334 |       return `${baseCommand} ${killCommand}`;
335 |     } catch (error) {
336 |       throw new Error(`${error.message}`);
337 |     }
338 |   }
339 | 
340 |   /**
341 |    * Builds the base command for listing the process associated with a port and method.
342 |    * 
343 |    * @param {string} method - The method (protocol) for the command (e.g., 'tcp' or 'udp').
344 |    * @param {number} port - The port number where the process is running.
345 |    * @returns {string} The base command to find the process ID (PID) of the process running on the specified port and protocol.
346 |    */
347 |   buildBaseCommand(method, port) {
348 |     return `lsof -i ${method}:${port} | grep ${method.toUpperCase()} | awk '{print $2}' | xargs`;
349 |   }
350 | 
351 |   /**
352 |    * Checks if a process is running on the specified port by using either a fast or normal check based on the current speed setting.
353 |    * 
354 |    * @param {number} port - The port number where the process is running.
355 |    * @returns {Promise<boolean>} A boolean indicating whether a process is running on the specified port.
356 |    */
357 |   async checkIfProcessExists(port) {
358 |     const isFastCheck = this.speed === 'fast';
359 |     const checkMethod = isFastCheck ? this.isExistFast : this.isExistNormal;
360 |     return await checkMethod.call(this, port);
361 |   }
362 | }
363 | 
364 | /**
365 |  * Main entry point to the script.
366 |  * @param {string | number | number[]} ports - Ports to be operated on.
367 |  * @param {Object} options - Options for the operation.
368 |  * @returns {Promise<void>}
369 |  */
370 | module.exports = async function (ports, options = {}) {
371 |   const portClient = new PortClient(ports, options);
372 |   return portClient.execute();
373 | }
374 | 
375 |
376 |
377 | 378 | 379 | 380 | 381 |
382 | 383 | 386 | 387 |
388 | 389 | 392 | 393 | 394 | 395 | 396 | 397 | -------------------------------------------------------------------------------- /docs/scripts/linenumber.js: -------------------------------------------------------------------------------- 1 | /*global document */ 2 | (() => { 3 | const source = document.getElementsByClassName('prettyprint source linenums'); 4 | let i = 0; 5 | let lineNumber = 0; 6 | let lineId; 7 | let lines; 8 | let totalLines; 9 | let anchorHash; 10 | 11 | if (source && source[0]) { 12 | anchorHash = document.location.hash.substring(1); 13 | lines = source[0].getElementsByTagName('li'); 14 | totalLines = lines.length; 15 | 16 | for (; i < totalLines; i++) { 17 | lineNumber++; 18 | lineId = `line${lineNumber}`; 19 | lines[i].id = lineId; 20 | if (lineId === anchorHash) { 21 | lines[i].className += ' selected'; 22 | } 23 | } 24 | } 25 | })(); 26 | -------------------------------------------------------------------------------- /docs/scripts/prettify/Apache-License-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /docs/scripts/prettify/lang-css.js: -------------------------------------------------------------------------------- 1 | PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", 2 | /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); 3 | -------------------------------------------------------------------------------- /docs/scripts/prettify/prettify.js: -------------------------------------------------------------------------------- 1 | var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; 2 | (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= 3 | [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), 9 | l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, 10 | q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, 11 | q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, 12 | "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), 13 | a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} 14 | for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], 18 | "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], 19 | H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], 20 | J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ 21 | I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), 22 | ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", 23 | /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), 24 | ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", 25 | hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= 26 | !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p th:last-child { border-right: 1px solid #ddd; } 224 | 225 | .ancestors, .attribs { color: #999; } 226 | .ancestors a, .attribs a 227 | { 228 | color: #999 !important; 229 | text-decoration: none; 230 | } 231 | 232 | .clear 233 | { 234 | clear: both; 235 | } 236 | 237 | .important 238 | { 239 | font-weight: bold; 240 | color: #950B02; 241 | } 242 | 243 | .yes-def { 244 | text-indent: -1000px; 245 | } 246 | 247 | .type-signature { 248 | color: #aaa; 249 | } 250 | 251 | .name, .signature { 252 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 253 | } 254 | 255 | .details { margin-top: 14px; border-left: 2px solid #DDD; } 256 | .details dt { width: 120px; float: left; padding-left: 10px; padding-top: 6px; } 257 | .details dd { margin-left: 70px; } 258 | .details ul { margin: 0; } 259 | .details ul { list-style-type: none; } 260 | .details li { margin-left: 30px; padding-top: 6px; } 261 | .details pre.prettyprint { margin: 0 } 262 | .details .object-value { padding-top: 0; } 263 | 264 | .description { 265 | margin-bottom: 1em; 266 | margin-top: 1em; 267 | } 268 | 269 | .code-caption 270 | { 271 | font-style: italic; 272 | font-size: 107%; 273 | margin: 0; 274 | } 275 | 276 | .source 277 | { 278 | border: 1px solid #ddd; 279 | width: 80%; 280 | overflow: auto; 281 | } 282 | 283 | .prettyprint.source { 284 | width: inherit; 285 | } 286 | 287 | .source code 288 | { 289 | font-size: 100%; 290 | line-height: 18px; 291 | display: block; 292 | padding: 4px 12px; 293 | margin: 0; 294 | background-color: #fff; 295 | color: #4D4E53; 296 | } 297 | 298 | .prettyprint code span.line 299 | { 300 | display: inline-block; 301 | } 302 | 303 | .prettyprint.linenums 304 | { 305 | padding-left: 70px; 306 | -webkit-user-select: none; 307 | -moz-user-select: none; 308 | -ms-user-select: none; 309 | user-select: none; 310 | } 311 | 312 | .prettyprint.linenums ol 313 | { 314 | padding-left: 0; 315 | } 316 | 317 | .prettyprint.linenums li 318 | { 319 | border-left: 3px #ddd solid; 320 | } 321 | 322 | .prettyprint.linenums li.selected, 323 | .prettyprint.linenums li.selected * 324 | { 325 | background-color: lightyellow; 326 | } 327 | 328 | .prettyprint.linenums li * 329 | { 330 | -webkit-user-select: text; 331 | -moz-user-select: text; 332 | -ms-user-select: text; 333 | user-select: text; 334 | } 335 | 336 | .params .name, .props .name, .name code { 337 | color: #4D4E53; 338 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 339 | font-size: 100%; 340 | } 341 | 342 | .params td.description > p:first-child, 343 | .props td.description > p:first-child 344 | { 345 | margin-top: 0; 346 | padding-top: 0; 347 | } 348 | 349 | .params td.description > p:last-child, 350 | .props td.description > p:last-child 351 | { 352 | margin-bottom: 0; 353 | padding-bottom: 0; 354 | } 355 | 356 | .disabled { 357 | color: #454545; 358 | } 359 | -------------------------------------------------------------------------------- /docs/styles/prettify-jsdoc.css: -------------------------------------------------------------------------------- 1 | /* JSDoc prettify.js theme */ 2 | 3 | /* plain text */ 4 | .pln { 5 | color: #000000; 6 | font-weight: normal; 7 | font-style: normal; 8 | } 9 | 10 | /* string content */ 11 | .str { 12 | color: #006400; 13 | font-weight: normal; 14 | font-style: normal; 15 | } 16 | 17 | /* a keyword */ 18 | .kwd { 19 | color: #000000; 20 | font-weight: bold; 21 | font-style: normal; 22 | } 23 | 24 | /* a comment */ 25 | .com { 26 | font-weight: normal; 27 | font-style: italic; 28 | } 29 | 30 | /* a type name */ 31 | .typ { 32 | color: #000000; 33 | font-weight: normal; 34 | font-style: normal; 35 | } 36 | 37 | /* a literal value */ 38 | .lit { 39 | color: #006400; 40 | font-weight: normal; 41 | font-style: normal; 42 | } 43 | 44 | /* punctuation */ 45 | .pun { 46 | color: #000000; 47 | font-weight: bold; 48 | font-style: normal; 49 | } 50 | 51 | /* lisp open bracket */ 52 | .opn { 53 | color: #000000; 54 | font-weight: bold; 55 | font-style: normal; 56 | } 57 | 58 | /* lisp close bracket */ 59 | .clo { 60 | color: #000000; 61 | font-weight: bold; 62 | font-style: normal; 63 | } 64 | 65 | /* a markup tag name */ 66 | .tag { 67 | color: #006400; 68 | font-weight: normal; 69 | font-style: normal; 70 | } 71 | 72 | /* a markup attribute name */ 73 | .atn { 74 | color: #006400; 75 | font-weight: normal; 76 | font-style: normal; 77 | } 78 | 79 | /* a markup attribute value */ 80 | .atv { 81 | color: #006400; 82 | font-weight: normal; 83 | font-style: normal; 84 | } 85 | 86 | /* a declaration */ 87 | .dec { 88 | color: #000000; 89 | font-weight: bold; 90 | font-style: normal; 91 | } 92 | 93 | /* a variable name */ 94 | .var { 95 | color: #000000; 96 | font-weight: normal; 97 | font-style: normal; 98 | } 99 | 100 | /* a function name */ 101 | .fun { 102 | color: #000000; 103 | font-weight: bold; 104 | font-style: normal; 105 | } 106 | 107 | /* Specify class=linenums on a pre to get line numbering */ 108 | ol.linenums { 109 | margin-top: 0; 110 | margin-bottom: 0; 111 | } 112 | -------------------------------------------------------------------------------- /docs/styles/prettify-tomorrow.css: -------------------------------------------------------------------------------- 1 | /* Tomorrow Theme */ 2 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 3 | /* Pretty printing styles. Used with prettify.js. */ 4 | /* SPAN elements with the classes below are added by prettyprint. */ 5 | /* plain text */ 6 | .pln { 7 | color: #4d4d4c; } 8 | 9 | @media screen { 10 | /* string content */ 11 | .str { 12 | color: #718c00; } 13 | 14 | /* a keyword */ 15 | .kwd { 16 | color: #8959a8; } 17 | 18 | /* a comment */ 19 | .com { 20 | color: #8e908c; } 21 | 22 | /* a type name */ 23 | .typ { 24 | color: #4271ae; } 25 | 26 | /* a literal value */ 27 | .lit { 28 | color: #f5871f; } 29 | 30 | /* punctuation */ 31 | .pun { 32 | color: #4d4d4c; } 33 | 34 | /* lisp open bracket */ 35 | .opn { 36 | color: #4d4d4c; } 37 | 38 | /* lisp close bracket */ 39 | .clo { 40 | color: #4d4d4c; } 41 | 42 | /* a markup tag name */ 43 | .tag { 44 | color: #c82829; } 45 | 46 | /* a markup attribute name */ 47 | .atn { 48 | color: #f5871f; } 49 | 50 | /* a markup attribute value */ 51 | .atv { 52 | color: #3e999f; } 53 | 54 | /* a declaration */ 55 | .dec { 56 | color: #f5871f; } 57 | 58 | /* a variable name */ 59 | .var { 60 | color: #c82829; } 61 | 62 | /* a function name */ 63 | .fun { 64 | color: #4271ae; } } 65 | /* Use higher contrast and text-weight for printable form. */ 66 | @media print, projection { 67 | .str { 68 | color: #060; } 69 | 70 | .kwd { 71 | color: #006; 72 | font-weight: bold; } 73 | 74 | .com { 75 | color: #600; 76 | font-style: italic; } 77 | 78 | .typ { 79 | color: #404; 80 | font-weight: bold; } 81 | 82 | .lit { 83 | color: #044; } 84 | 85 | .pun, .opn, .clo { 86 | color: #440; } 87 | 88 | .tag { 89 | color: #006; 90 | font-weight: bold; } 91 | 92 | .atn { 93 | color: #404; } 94 | 95 | .atv { 96 | color: #060; } } 97 | /* Style */ 98 | /* 99 | pre.prettyprint { 100 | background: white; 101 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 102 | font-size: 12px; 103 | line-height: 1.5; 104 | border: 1px solid #ccc; 105 | padding: 10px; } 106 | */ 107 | 108 | /* Specify class=linenums on a pre to get line numbering */ 109 | ol.linenums { 110 | margin-top: 0; 111 | margin-bottom: 0; } 112 | 113 | /* IE indents via margin-left */ 114 | li.L0, 115 | li.L1, 116 | li.L2, 117 | li.L3, 118 | li.L4, 119 | li.L5, 120 | li.L6, 121 | li.L7, 122 | li.L8, 123 | li.L9 { 124 | /* */ } 125 | 126 | /* Alternate shading for lines */ 127 | li.L1, 128 | li.L3, 129 | li.L5, 130 | li.L7, 131 | li.L9 { 132 | /* */ } 133 | -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | import http from 'http'; 2 | import isPortReachable from 'is-port-reachable'; 3 | import portUtil from './index.js'; 4 | 5 | const PORT = 3000; 6 | const SERVER_OPTIONS = { 7 | method: 'tcp', 8 | verbose: true, 9 | action: 'kill' 10 | }; 11 | 12 | async function checkPortAndStartServer(port) { 13 | try { 14 | const isOccupied = await isPortReachable(port, { host: 'localhost' }); 15 | console.log(`Port ${port} is ${isOccupied ? 'occupied' : 'available'}`); 16 | 17 | if (isOccupied) { 18 | console.log(`Attempting to free up port ${port}...`); 19 | await portUtil(port, { action: 'kill', method: 'tcp', verbose: true }); 20 | } 21 | 22 | startServer(port); 23 | } catch (error) { 24 | console.error(`Error checking port ${port}:`, error); 25 | } 26 | } 27 | 28 | function startServer(port) { 29 | const server = http.createServer((req, res) => { 30 | res.writeHead(200, { 'Content-Type': 'text/plain' }); 31 | res.end('Hi!'); 32 | }); 33 | 34 | server.listen(port, () => { 35 | console.log(`Server is listening on port ${port}`); 36 | }); 37 | } 38 | 39 | (async function main() { 40 | try { 41 | console.log('Starting port utility...'); 42 | await portUtil(PORT, SERVER_OPTIONS); 43 | console.log('Port existence check completed.'); 44 | await checkPortAndStartServer(PORT); 45 | } catch (error) { 46 | console.error('Error during initialization:', error); 47 | } 48 | })(); 49 | -------------------------------------------------------------------------------- /image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fix2015/port-client/35ce4cd3c6bbec07b1730d906e110c3bcaeaf3c6/image.png -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const sh = require('shell-exec'); 4 | const readline = require('readline') 5 | 6 | /** 7 | * A class to manage port operations (kill, check, or verify existence). 8 | */ 9 | class PortClient { 10 | /** 11 | * Creates an instance of PortClient 12 | * @param {string | number | number[]} ports - Ports to be checked or killed. 13 | * @param {Object} options - Options for the operation. 14 | */ 15 | constructor(ports, { 16 | method = 'tcp', 17 | action = 'check', 18 | interactive = false, 19 | dryRun = false, 20 | verbose = false, 21 | graceful = false, 22 | filter = null, 23 | range = null, 24 | speed = 'safe', 25 | } = {}) { 26 | this.ports = ports; 27 | this.method = method; 28 | this.action = action; 29 | this.interactive = interactive; 30 | this.dryRun = dryRun; 31 | this.verbose = verbose; 32 | this.graceful = graceful; 33 | this.filter = filter; 34 | this.range = range; 35 | this.speed = speed; 36 | this.platform = process.platform; 37 | } 38 | 39 | /** 40 | * Logs messages if verbose mode is enabled. 41 | * @param {string} message - The message to log. 42 | */ 43 | log(message) { 44 | if (this.verbose) { 45 | console.log(message); 46 | } 47 | } 48 | 49 | /** 50 | * Parses the provided ports into an array of valid ports. 51 | * @returns {number[]} The parsed ports. 52 | */ 53 | parsePorts() { 54 | if (Array.isArray(this.ports)) { 55 | return this.ports.map(Number).filter(Boolean); 56 | } else if (this.range) { 57 | const [start, end] = this.range.split('-').map(Number); 58 | return Array.from({ length: end - start + 1 }, (_, i) => start + i); 59 | } else { 60 | const port = Number(this.ports); 61 | return port ? [port] : []; 62 | } 63 | } 64 | 65 | /** 66 | * Executes the port operation based on the action flag. 67 | * @returns {Promise} 68 | */ 69 | async execute() { 70 | const parsedPorts = this.parsePorts(); 71 | if (parsedPorts.length === 0) { 72 | throw new Error('Invalid or no port(s) provided.'); 73 | } 74 | 75 | if (this.dryRun) { 76 | this.success(`Dry run: Ports to operate on - ${parsedPorts.join(', ')}`); 77 | return; 78 | } 79 | 80 | if (this.interactive) { 81 | const activePorts = await this.listActivePorts(); 82 | const selectedPorts = await this.promptUserToSelectPorts(activePorts); 83 | return this.handlePorts(selectedPorts); 84 | } 85 | 86 | return this.handlePorts(parsedPorts); 87 | } 88 | 89 | /** 90 | * Lists active ports based on the platform and speed flag. 91 | * @returns {Promise} List of active ports. 92 | */ 93 | async listActivePorts() { 94 | const command = this.platform === 'win32' 95 | ? 'netstat -nao' 96 | : (this.speed === 'fast' 97 | ? `lsof -i :${this.ports}` 98 | : 'lsof -i -P -n'); 99 | 100 | try { 101 | const { stdout } = await sh(command); 102 | const lines = stdout.split('\n'); 103 | return this.platform === 'win32' ? this.parseWindowsPorts(lines) : this.parseUnixPorts(lines); 104 | } catch (error) { 105 | throw new Error(`Failed to list active ports: ${error.message}`); 106 | } 107 | } 108 | 109 | /** 110 | * Parses active ports for Windows. 111 | * @param {string[]} lines - The output lines from the netstat command. 112 | * @returns {string[]} The parsed active ports. 113 | */ 114 | parseWindowsPorts(lines) { 115 | const regex = new RegExp(`^ *${this.method.toUpperCase()} *[^ ]*:(\\d+),`, 'gm'); 116 | return lines.reduce((acc, line) => { 117 | const match = line.match(regex); 118 | if (match && match[1] && !acc.includes(match[1])) { 119 | acc.push(match[1]); 120 | } 121 | return acc; 122 | }, []); 123 | } 124 | 125 | /** 126 | * Parses active ports for Unix-like systems. 127 | * @param {string[]} lines - The output lines from the lsof command. 128 | * @returns {string[]} The parsed active ports. 129 | */ 130 | parseUnixPorts(lines) { 131 | 132 | const regex = /(?<=:\d{1,5})->|\b\d{1,5}(?=->|\s+\(CLOSED\)|\s+\(ESTABLISHED\)|\s+\(LISTEN\))/g; 133 | 134 | return lines.flatMap(line => line.match(regex)).filter(Boolean); 135 | 136 | } 137 | 138 | /** 139 | * Prompts the user to select ports interactively. 140 | * @param {string[]} activePorts - List of active ports to choose from. 141 | * @returns {Promise} The selected ports. 142 | */ 143 | promptUserToSelectPorts(activePorts) { 144 | return new Promise((resolve) => { 145 | const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); 146 | 147 | activePorts.forEach((port, index) => { 148 | this.success(`${index + 1}. ${port}`); 149 | }); 150 | 151 | rl.question('Select ports to operate on (comma-separated indices): ', (answer) => { 152 | const indices = answer.split(',').map(Number); 153 | const selectedPorts = indices.map((index) => activePorts[index - 1]).filter(Boolean); 154 | rl.close(); 155 | resolve(selectedPorts); 156 | }); 157 | }); 158 | } 159 | 160 | /** 161 | * Handles the action on a list of ports based on the specified action type. 162 | * 163 | * @param {number[]} ports - The list of port numbers to act upon. 164 | * @returns {Promise} The result of the action performed. 165 | */ 166 | async handlePorts(ports) { 167 | switch (this.action) { 168 | case 'check': 169 | case 'isExist': 170 | return this.showPortInfo(ports); 171 | 172 | case 'kill': 173 | return this.killPorts(ports); 174 | 175 | default: 176 | throw new Error(`Unknown action: ${this.action}`); 177 | } 178 | } 179 | 180 | async isExistFast(port) { 181 | const { stdout } = await sh(`lsof -i :${port}`); 182 | 183 | return stdout.includes('LISTEN'); 184 | } 185 | 186 | async isExistNormal(port) { 187 | const activePorts = await this.listActivePorts(); 188 | 189 | return activePorts.includes(String(port)); 190 | } 191 | 192 | /** 193 | * Logs a success message in green. 194 | * 195 | * @param {string} message - The success message to log. 196 | * @returns {void} 197 | */ 198 | success(message) { 199 | console.log('\x1b[32m%s\x1b[0m', `${message}`); 200 | } 201 | 202 | /** 203 | * Logs an error message in red. 204 | * 205 | * @param {string} message - The error message to log. 206 | * @returns {void} 207 | */ 208 | error(message) { 209 | console.log('\x1b[31m%s\x1b[0m', `${message}`); 210 | } 211 | 212 | /** 213 | * Checks and logs the status of each port, indicating whether it is active or not. 214 | * 215 | * @param {number[]} ports - An array of port numbers to check for activity. 216 | */ 217 | async showPortInfo(ports) { 218 | for (const port of ports) { 219 | try { 220 | const isActive = await this.checkPortStatus(port); 221 | 222 | this.success(isActive ? `Port ${port} is active.` : `Port ${port} is not active.`); 223 | } catch (error) { 224 | this.error(`Error checking port ${port}: ${error.message}`); 225 | } 226 | } 227 | } 228 | 229 | /** 230 | * Checks whether a given port is active based on the current speed setting. 231 | * 232 | * @param {number} port - The port number to check. 233 | * @returns {Promise} A promise that resolves to a boolean indicating whether the port is active. 234 | */ 235 | async checkPortStatus(port) { 236 | const checkMethod = this.speed === 'fast' ? this.isExistFast : this.isExistNormal; 237 | return await checkMethod.call(this, port); 238 | } 239 | 240 | /** 241 | * Kills the specified ports. 242 | * @param {number[]} ports - The ports to kill. 243 | * @returns {Promise} 244 | */ 245 | async killPorts(ports) { 246 | for (const port of ports) { 247 | try { 248 | const command = this.platform === 'win32' 249 | ? await this.getWindowsKillCommand(port) 250 | : await this.getUnixKillCommand(port, this.method, this.graceful); 251 | 252 | this.log(`Executing: ${command}`); 253 | const result = await sh(command); 254 | this.success(`Successfully killed port ${port} ${result.stdout}`); 255 | } catch (error) { 256 | this.error(`Failed to kill port ${port}: ${error.message}`); 257 | } 258 | } 259 | } 260 | 261 | /** 262 | * Gets the Windows command to kill a port. 263 | * @param {number} port - The port to kill. 264 | * @returns {string} The Windows kill command. 265 | */ 266 | async getWindowsKillCommand(port) { 267 | try { 268 | const { stdout } = await sh('netstat -nao'); 269 | const lines = stdout.split('\n'); 270 | const regex = new RegExp(`^ *${this.method.toUpperCase()} *[^ ]*:${port},`, 'gm'); 271 | const linesWithPort = lines.filter(line => regex.test(line)); 272 | 273 | const pids = linesWithPort.reduce((acc, line) => { 274 | const pidMatch = line.match(/(\d+)\w*/); 275 | if (pidMatch) acc.push(pidMatch[1]); 276 | return acc; 277 | }, []); 278 | 279 | return `TaskKill /F /PID ${pids.join(' /PID ')}`; 280 | } catch (error) { 281 | throw new Error(`Failed to get Windows kill command: ${error.message}`); 282 | } 283 | } 284 | 285 | /** 286 | * Constructs the Unix command to kill a process running on a specified port. 287 | * The command will either gracefully or forcefully terminate the process, depending on the `graceful` parameter. 288 | * 289 | * @param {number} port - The port number where the process is running. 290 | * @param {string} [method='tcp'] - The method (protocol) for the command (e.g., 'tcp' or 'udp'). Defaults to 'tcp'. 291 | * @param {boolean} [graceful=false] - Whether to send a graceful kill signal (`true`) or a forceful one (`false`). Defaults to `false` (forceful kill). 292 | * @returns {Promise} The full Unix command string to kill the process. 293 | * @throws {Error} Throws an error if no process is found running on the specified port. 294 | */ 295 | async getUnixKillCommand(port, method = 'tcp', graceful = false) { 296 | const baseCommand = this.buildBaseCommand(method, port); 297 | const killCommand = graceful ? 'kill' : 'kill -9'; 298 | 299 | try { 300 | const processExists = await this.checkIfProcessExists(port); 301 | 302 | if (!processExists) { 303 | throw new Error('No process running on port'); 304 | } 305 | 306 | return `${baseCommand} ${killCommand}`; 307 | } catch (error) { 308 | throw new Error(`${error.message}`); 309 | } 310 | } 311 | 312 | /** 313 | * Builds the base command for listing the process associated with a port and method. 314 | * 315 | * @param {string} method - The method (protocol) for the command (e.g., 'tcp' or 'udp'). 316 | * @param {number} port - The port number where the process is running. 317 | * @returns {string} The base command to find the process ID (PID) of the process running on the specified port and protocol. 318 | */ 319 | buildBaseCommand(method, port) { 320 | return `lsof -i ${method}:${port} | grep ${method.toUpperCase()} | awk '{print $2}' | xargs`; 321 | } 322 | 323 | /** 324 | * Checks if a process is running on the specified port by using either a fast or normal check based on the current speed setting. 325 | * 326 | * @param {number} port - The port number where the process is running. 327 | * @returns {Promise} A boolean indicating whether a process is running on the specified port. 328 | */ 329 | async checkIfProcessExists(port) { 330 | const isFastCheck = this.speed === 'fast'; 331 | const checkMethod = isFastCheck ? this.isExistFast : this.isExistNormal; 332 | return await checkMethod.call(this, port); 333 | } 334 | } 335 | 336 | /** 337 | * Main entry point to the script. 338 | * @param {string | number | number[]} ports - Ports to be operated on. 339 | * @param {Object} options - Options for the operation. 340 | * @returns {Promise} 341 | */ 342 | module.exports = async function (ports, options = {}) { 343 | const portClient = new PortClient(ports, options); 344 | return portClient.execute(); 345 | } 346 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "port-client", 3 | "version": "2.0.1", 4 | "description": "A powerful utility for managing processes on specified ports, including options for checking port status, killing processes, handling multiple ports, enabling interactive mode, and supporting graceful termination.", 5 | "main": "dist/index.js", 6 | "scripts": { 7 | "build": "npx tsc", 8 | "build:prod": "ncc build index.js -o dist && terser dist/index.js -o dist/index.js --compress --mangle", 9 | "test": "echo \"Error: no test specified\" && exit 1" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/fix2015/clean-port.git" 14 | }, 15 | "bin": { 16 | "port-client": "cli.js" 17 | }, 18 | "keywords": [ 19 | "kill-port", 20 | "port-management", 21 | "cli", 22 | "process-termination", 23 | "tcp", 24 | "udp", 25 | "interactive-cli", 26 | "development-tool", 27 | "port-client", 28 | "port-manager" 29 | ], 30 | "author": "Semianchuk Vitalii", 31 | "license": "ISC", 32 | "bugs": { 33 | "url": "https://github.com/fix2015/clean-port/issues" 34 | }, 35 | "homepage": "https://github.com/fix2015/clean-port#readme", 36 | "dependencies": { 37 | "get-them-args": "^1.3.2", 38 | "is-port-reachable": "^4.0.0", 39 | "readline": "^1.3.0", 40 | "shell-exec": "^1.0.2" 41 | }, 42 | "devDependencies": { 43 | "@types/node": "^22.10.7", 44 | "@vercel/ncc": "^0.38.3", 45 | "terser": "^5.37.0", 46 | "typescript": "^5.7.3" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /pnpm-lock.yaml: -------------------------------------------------------------------------------- 1 | lockfileVersion: '9.0' 2 | 3 | settings: 4 | autoInstallPeers: true 5 | excludeLinksFromLockfile: false 6 | 7 | importers: 8 | 9 | .: 10 | dependencies: 11 | get-them-args: 12 | specifier: ^1.3.2 13 | version: 1.3.2 14 | is-port-reachable: 15 | specifier: ^4.0.0 16 | version: 4.0.0 17 | readline: 18 | specifier: ^1.3.0 19 | version: 1.3.0 20 | shell-exec: 21 | specifier: ^1.0.2 22 | version: 1.0.2 23 | 24 | packages: 25 | 26 | get-them-args@1.3.2: 27 | resolution: {integrity: sha512-LRn8Jlk+DwZE4GTlDbT3Hikd1wSHgLMme/+7ddlqKd7ldwR6LjJgTVWzBnR01wnYGe4KgrXjg287RaI22UHmAw==} 28 | 29 | is-port-reachable@4.0.0: 30 | resolution: {integrity: sha512-9UoipoxYmSk6Xy7QFgRv2HDyaysmgSG75TFQs6S+3pDM7ZhKTF/bskZV+0UlABHzKjNVhPjYCLfeZUEg1wXxig==} 31 | engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} 32 | 33 | readline@1.3.0: 34 | resolution: {integrity: sha512-k2d6ACCkiNYz222Fs/iNze30rRJ1iIicW7JuX/7/cozvih6YCkFZH+J6mAFDVgv0dRBaAyr4jDqC95R2y4IADg==} 35 | 36 | shell-exec@1.0.2: 37 | resolution: {integrity: sha512-jyVd+kU2X+mWKMmGhx4fpWbPsjvD53k9ivqetutVW/BQ+WIZoDoP4d8vUMGezV6saZsiNoW2f9GIhg9Dondohg==} 38 | 39 | snapshots: 40 | 41 | get-them-args@1.3.2: {} 42 | 43 | is-port-reachable@4.0.0: {} 44 | 45 | readline@1.3.0: {} 46 | 47 | shell-exec@1.0.2: {} 48 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import sh from 'shell-exec'; 2 | import readline from 'readline'; 3 | 4 | class PortClient { 5 | ports: string | number | number[]; 6 | method: string; 7 | action: string; 8 | interactive: boolean; 9 | dryRun: boolean; 10 | verbose: boolean; 11 | graceful: boolean; 12 | filter: string | null; 13 | range: string | null; 14 | speed: string; 15 | platform: string; 16 | 17 | constructor( 18 | ports: string | number | number[], 19 | { 20 | method = 'tcp', 21 | action = 'check', 22 | interactive = false, 23 | dryRun = false, 24 | verbose = false, 25 | graceful = false, 26 | filter = null, 27 | range = null, 28 | speed = 'safe', 29 | }: { 30 | method?: string; 31 | action?: string; 32 | interactive?: boolean; 33 | dryRun?: boolean; 34 | verbose?: boolean; 35 | graceful?: boolean; 36 | filter?: string | null; 37 | range?: string | null; 38 | speed?: string; 39 | } = {} 40 | ) { 41 | this.ports = ports; 42 | this.method = method; 43 | this.action = action; 44 | this.interactive = interactive; 45 | this.dryRun = dryRun; 46 | this.verbose = verbose; 47 | this.graceful = graceful; 48 | this.filter = filter; 49 | this.range = range; 50 | this.speed = speed; 51 | this.platform = process.platform; 52 | } 53 | 54 | log(message: string): void { 55 | if (this.verbose) { 56 | console.log(message); 57 | } 58 | } 59 | 60 | parsePorts(): number[] { 61 | if (Array.isArray(this.ports)) { 62 | return this.ports.map(Number).filter(Boolean); 63 | } else if (this.range) { 64 | const [start, end] = this.range.split('-').map(Number); 65 | return Array.from({ length: end - start + 1 }, (_, i) => start + i); 66 | } else { 67 | const port = Number(this.ports); 68 | return port ? [port] : []; 69 | } 70 | } 71 | 72 | async execute(): Promise { 73 | const parsedPorts = this.parsePorts(); 74 | if (parsedPorts.length === 0) { 75 | throw new Error('Invalid or no port(s) provided.'); 76 | } 77 | 78 | if (this.dryRun) { 79 | this.success(`Dry run: Ports to operate on - ${parsedPorts.join(', ')}`); 80 | return; 81 | } 82 | 83 | if (this.interactive) { 84 | const activePorts = await this.listActivePorts(); 85 | const selectedPorts = await this.promptUserToSelectPorts(activePorts); 86 | return this.handlePorts(selectedPorts.map(Number)); // Ensure it's a number[] 87 | } 88 | 89 | return this.handlePorts(parsedPorts); 90 | } 91 | 92 | async handlePorts(ports: number[]) { 93 | switch (this.action) { 94 | case 'check': 95 | case 'isExist': 96 | return this.showPortInfo(ports); 97 | 98 | case 'kill': 99 | return this.killPorts(ports); 100 | 101 | default: 102 | throw new Error(`Unknown action: ${this.action}`); 103 | } 104 | } 105 | 106 | async listActivePorts(): Promise { 107 | const command = this.platform === 'win32' 108 | ? 'netstat -nao' 109 | : (this.speed === 'fast' 110 | ? `lsof -i :${this.ports}` 111 | : 'lsof -i -P -n'); 112 | 113 | try { 114 | const { stdout } = await sh(command); 115 | const lines = stdout.split('\n'); 116 | return this.platform === 'win32' ? this.parseWindowsPorts(lines) : this.parseUnixPorts(lines); 117 | } catch (error: any) { 118 | throw new Error(`Failed to list active ports: ${(error as Error).message}`); 119 | } 120 | } 121 | 122 | parseWindowsPorts(lines: string[]): string[] { 123 | const regex = new RegExp(`^ *${this.method.toUpperCase()} *[^ ]*:(\\d+),`, 'gm'); 124 | return lines.reduce((acc: string[], line: string) => { 125 | const match = line.match(regex); 126 | if (match && match[1] && !acc.includes(match[1])) { 127 | acc.push(match[1]); 128 | } 129 | return acc; 130 | }, []); 131 | } 132 | 133 | parseUnixPorts(lines: string[]): string[] { 134 | const regex = /(?<=:\d{1,5})->|\b\d{1,5}(?=->|\s+\(CLOSED\)|\s+\(ESTABLISHED\)|\s+\(LISTEN\))/g; 135 | return lines.flatMap((line: string) => line.match(regex) || []).filter(Boolean); 136 | } 137 | 138 | async promptUserToSelectPorts(activePorts: string[]): Promise { 139 | return new Promise((resolve) => { 140 | const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); 141 | 142 | activePorts.forEach((port, index) => { 143 | this.success(`${index + 1}. ${port}`); 144 | }); 145 | 146 | rl.question('Select ports to operate on (comma-separated indices): ', (answer) => { 147 | const indices = answer.split(',').map(Number); 148 | const selectedPorts = indices.map((index) => activePorts[index - 1]).filter(Boolean); 149 | rl.close(); 150 | resolve(selectedPorts.map(Number)); // Ensure it's a number[] 151 | }); 152 | }); 153 | } 154 | 155 | success(message: string): void { 156 | console.log('\x1b[32m%s\x1b[0m', `${message}`); 157 | } 158 | 159 | error(message: string): void { 160 | console.log('\x1b[31m%s\x1b[0m', `${message}`); 161 | } 162 | 163 | async showPortInfo(ports: number[]): Promise { 164 | for (const port of ports) { 165 | try { 166 | const isActive = await this.checkPortStatus(port); 167 | this.success(isActive ? `Port ${port} is active.` : `Port ${port} is not active.`); 168 | } catch (error: any) { 169 | this.error(`Error checking port ${port}: ${(error as Error).message}`); 170 | } 171 | } 172 | } 173 | 174 | async isExistFast(port: number): Promise { 175 | // Fast method: using lsof (this is an example, you can replace with your own fast method) 176 | try { 177 | const { stdout } = await sh(`lsof -i tcp:${port}`); 178 | return stdout.trim().length > 0; 179 | } catch (error: any) { 180 | return false; 181 | } 182 | } 183 | 184 | async checkPortStatus(port: number): Promise { 185 | const checkMethod = this.speed === 'fast' ? this.isExistFast : this.isExistNormal; 186 | return await checkMethod.call(this, port); 187 | } 188 | 189 | async killPorts(ports: number[]): Promise { 190 | for (const port of ports) { 191 | try { 192 | const command = this.platform === 'win32' 193 | ? await this.getWindowsKillCommand(port) 194 | : await this.getUnixKillCommand(port, this.method, this.graceful); 195 | 196 | this.log(`Executing: ${command}`); 197 | const result = await sh(command); 198 | this.success(`Successfully killed port ${port} ${result.stdout}`); 199 | } catch (error: any) { 200 | this.error(`Failed to kill port ${port}: ${(error as Error).message}`); 201 | } 202 | } 203 | } 204 | 205 | async getWindowsKillCommand(port: number): Promise { 206 | try { 207 | const { stdout } = await sh('netstat -nao'); 208 | const lines = stdout.split('\n'); 209 | const regex = new RegExp(`^ *${this.method.toUpperCase()} *[^ ]*:${port},`, 'gm'); 210 | const linesWithPort = lines.filter((line: string) => regex.test(line)); 211 | 212 | const pids = linesWithPort.reduce((acc: string[], line: string) => { 213 | const pidMatch = line.match(/(\d+)\w*/); 214 | if (pidMatch) acc.push(pidMatch[1]); 215 | return acc; 216 | }, []); 217 | 218 | return `TaskKill /F /PID ${pids.join(' /PID ')}`; 219 | } catch (error: any) { 220 | throw new Error(`Failed to get Windows kill command: ${(error as Error).message}`); 221 | } 222 | } 223 | 224 | async getUnixKillCommand(port: number, method: string = 'tcp', graceful: boolean = false): Promise { 225 | const baseCommand = this.buildBaseCommand(method, port); 226 | const killCommand = graceful ? 'kill' : 'kill -9'; 227 | 228 | try { 229 | const processExists = await this.checkIfProcessExists(port); 230 | 231 | if (!processExists) { 232 | throw new Error('No process running on port'); 233 | } 234 | 235 | return `${baseCommand} ${killCommand}`; 236 | } catch (error: any) { 237 | throw new Error(`${(error as Error).message}`); 238 | } 239 | } 240 | 241 | async isExistNormal(port: number): Promise { 242 | // Normal method: using netstat (this is an example, you can replace with your own normal method) 243 | try { 244 | const { stdout } = await sh(`netstat -na | grep :${port}`); 245 | return stdout.trim().length > 0; 246 | } catch (error: any) { 247 | return false; 248 | } 249 | } 250 | 251 | buildBaseCommand(method: string, port: number): string { 252 | return `lsof -t -i ${method}:${port}`; 253 | } 254 | 255 | async checkIfProcessExists(port: number): Promise { 256 | try { 257 | const { stdout } = await sh(`lsof -t -i tcp:${port}`); 258 | return stdout.trim().length > 0; 259 | } catch (error: any) { 260 | throw new Error(`Failed to check if process exists on port ${port}`); 261 | } 262 | } 263 | } 264 | 265 | // Step 2: Wrap the invocation logic in an exported function 266 | async function runPortClient (ports: number | number[], options = {}) { 267 | const portClient = new PortClient(ports, options); 268 | return portClient.execute(); 269 | } 270 | 271 | module.exports = runPortClient; 272 | -------------------------------------------------------------------------------- /src/shell-exec.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'shell-exec'; 2 | -------------------------------------------------------------------------------- /test/portClient.test.js: -------------------------------------------------------------------------------- 1 | // portClient.test.js 2 | const sh = require('shell-exec'); // Shell execution module 3 | const readline = require('readline'); 4 | const PortClient = require('../index.js'); // Assuming the class is in portClient.js 5 | 6 | jest.mock('shell-exec'); 7 | jest.mock('readline'); 8 | 9 | // Test suite for PortClient 10 | describe('PortClient Tests', () => { 11 | afterEach(() => { 12 | jest.clearAllMocks(); 13 | }); 14 | 15 | test('should parse single port correctly', () => { 16 | const client = new PortClient(8080, { verbose: true }); 17 | const parsedPorts = client.parsePorts(); 18 | expect(parsedPorts).toEqual([8080]); 19 | }); 20 | 21 | test('should parse range of ports correctly', () => { 22 | const client = new PortClient(null, { range: '8080-8082', verbose: true }); 23 | const parsedPorts = client.parsePorts(); 24 | expect(parsedPorts).toEqual([8080, 8081, 8082]); 25 | }); 26 | 27 | test('should parse an array of ports correctly', () => { 28 | const client = new PortClient([8080, 8081, 8082], { verbose: true }); 29 | const parsedPorts = client.parsePorts(); 30 | expect(parsedPorts).toEqual([8080, 8081, 8082]); 31 | }); 32 | 33 | test('should throw error if no valid ports provided', async () => { 34 | const client = new PortClient(null, { verbose: true }); 35 | await expect(client.execute()).rejects.toThrow('Invalid or no port(s) provided.'); 36 | }); 37 | 38 | test('should list active ports for Unix-like systems', async () => { 39 | const mockShellResponse = { stdout: 'tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN' }; 40 | sh.mockResolvedValue(mockShellResponse); 41 | 42 | const client = new PortClient(8080, { method: 'tcp', speed: 'safe' }); 43 | const activePorts = await client.listActivePorts(); 44 | expect(activePorts).toEqual(['8080']); 45 | }); 46 | 47 | test('should list active ports for Windows systems', async () => { 48 | const mockShellResponse = { stdout: 'TCP 0.0.0.0:8080 0.0.0.0:* LISTENING 1234' }; 49 | sh.mockResolvedValue(mockShellResponse); 50 | 51 | const client = new PortClient(8080, { method: 'tcp', speed: 'safe' }); 52 | client.platform = 'win32'; // Mock Windows platform 53 | const activePorts = await client.listActivePorts(); 54 | expect(activePorts).toEqual(['8080']); 55 | }); 56 | 57 | test('should correctly handle dry run', async () => { 58 | const client = new PortClient(8080, { dryRun: true, verbose: true }); 59 | const consoleSpy = jest.spyOn(console, 'log').mockImplementation(); 60 | 61 | await client.execute(); 62 | 63 | expect(consoleSpy).toHaveBeenCalledWith('Dry run: Ports to operate on - 8080'); 64 | consoleSpy.mockRestore(); 65 | }); 66 | 67 | test('should successfully kill ports', async () => { 68 | const mockShellResponse = { stdout: 'Process killed successfully' }; 69 | sh.mockResolvedValue(mockShellResponse); 70 | 71 | const client = new PortClient(8080, { action: 'kill', verbose: true }); 72 | const consoleSpy = jest.spyOn(console, 'log').mockImplementation(); 73 | 74 | await client.execute(); 75 | 76 | expect(consoleSpy).toHaveBeenCalledWith('Executing: kill -9 8080'); 77 | expect(consoleSpy).toHaveBeenCalledWith('Successfully killed port 8080 Process killed successfully'); 78 | consoleSpy.mockRestore(); 79 | }); 80 | 81 | test('should handle error when killing non-existent port', async () => { 82 | const mockShellResponse = { stdout: '' }; 83 | sh.mockRejectedValue(new Error('No process found for port')); 84 | 85 | const client = new PortClient(8080, { action: 'kill', verbose: true }); 86 | const consoleSpy = jest.spyOn(console, 'log').mockImplementation(); 87 | 88 | await client.execute(); 89 | 90 | expect(consoleSpy).toHaveBeenCalledWith('Failed to kill port 8080: No process found for port'); 91 | consoleSpy.mockRestore(); 92 | }); 93 | 94 | test('should ask user to select ports interactively', async () => { 95 | const mockActivePorts = ['8080', '8081', '8082']; 96 | const mockSelectedPorts = [8080, 8081]; 97 | 98 | const rlMock = { 99 | question: jest.fn().mockImplementation((query, callback) => callback('1,2')), 100 | close: jest.fn(), 101 | }; 102 | readline.createInterface.mockReturnValue(rlMock); 103 | 104 | const client = new PortClient(8080, { interactive: true, verbose: true }); 105 | const handlePortsSpy = jest.spyOn(client, 'handlePorts'); 106 | 107 | await client.execute(); 108 | 109 | expect(handlePortsSpy).toHaveBeenCalledWith(mockSelectedPorts); 110 | expect(rlMock.close).toHaveBeenCalled(); 111 | }); 112 | }); 113 | 114 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES6", // Set target JavaScript version (ES6 for modern features) 4 | "module": "CommonJS", // Use CommonJS module system (default for Node.js) 5 | "outDir": "./dist", // Output compiled files to 'dist' folder 6 | "rootDir": "./src", // Your TypeScript source code is in the 'src' folder 7 | "strict": true, // Enable strict type-checking options 8 | "esModuleInterop": true, // Allows default import of CommonJS modules 9 | "skipLibCheck": true, // Skip checking library files for faster builds 10 | "forceConsistentCasingInFileNames": true // Ensure consistent casing for file names 11 | }, 12 | "include": ["src/**/*.ts"], // Include all .ts files in the 'src' folder 13 | "exclude": ["node_modules"] // Exclude 'node_modules' folder 14 | } 15 | --------------------------------------------------------------------------------