TL;DR
This is a script to delete a running node process, if one exists.
#!/bin/bash
lsof_output=$(lsof -i :3000)
if [ -n "$lsof_output" ]; then
node_line=$(echo "$lsof_output" | grep "node")
if [ -n "$node_line" ]; then
pid=$(echo "$node_line" | awk '{print $2}')
# Kill the Node.js process with SIGKILL (9)
echo "Killing Node.js process with PID $pid"
kill -9 $pid
echo "Node.js process killed."
else
echo "No Node.js process found on port 3000."
fi
else
echo "No process is listening on port 3000."
fi
It's very useful when running npm start
to spin up a React app and you get a Port 3000 is already in use
message.
You can also pair it with the npm start
command right after it for a better experience. If the port is not in use the script will not do anything.
I went ahead and created an alias for even more convenience, and to do that follow these steps:
- Open your
.zshrc
or.bashrc
with:code ~/.zshrc
- Add
alias killnode="killnode.sh && npm start"
- Run it from you app's folder
Enjoy 🦾
Top comments (0)