Introduction to kill-port
The kill-port
utility is a powerful command-line tool that helps developers manage network ports by terminating processes utilizing specific ports. This is especially useful for resolving port conflicts that can disrupt local development environments. In this article, we will explore dozens of useful APIs provided by kill-port
and show you how to leverage them with code snippets and application examples.
Common kill-port APIs
kill-port
: The most basic command to kill a port.kill-port --tcp [port]
: Kills TCP connections on the specified port.kill-port --udp [port]
: Terminates UDP connections on the given port.kill-port -f [port]
: Forcefully kills processes using the specified port.kill-port -c [port]
: Confirms whether the port is successfully freed.
Code Snippets
Here are some practical examples to help you get started with kill-port
:
// Killing a TCP port
const { exec } = require('child_process');
exec('kill-port --tcp 3000', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
// Killing a UDP port
exec('kill-port --udp 4000', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
// Kill port forcefully
exec('kill-port -f 5000', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
App Example using kill-port APIs
Below is a simple web application example that integrates kill-port
APIs to manage port conflicts:
const express = require('express');
const { exec } = require('child_process');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/kill-port/:port', (req, res) => {
const port = req.params.port;
exec(`kill-port --tcp ${port}`, (error, stdout, stderr) => {
if (error) {
res.status(500).send(`Failed to kill port ${port}: ${error}`);
return;
}
res.send(`Successfully killed port ${port}`);
});
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This application provides an HTTP endpoint to terminate processes on a specified port. Simply send a GET request to /kill-port/:port
to free up the port.
By leveraging kill-port
, you can streamline port management tasks and ensure a smoother development workflow.
Hash: 97fbffb93b241745ca749fb9e1e9fdf53c1dbbd71cd97f1e204d0c0c681637b8