Npm script that finds and kills port that's in use - node.js

I'm on a windows machine and every time I quit a node process, and try to restart again I get a Error: listen EADDRINUSE :::8004
I then have to do
netstat -o -n -a | findstr 0.0:8004
taskkill /F /PID <PID>
How can I write a script that finds and kills the PID by just doing npm kill?

1) the problem isn't about killing the server, it's about closing the port properly upon exiting. The program is obviously missing a server.close() in a process.on('exit', ..) and process.on('uncaughtException', ..).
2) the first argument allowed next to npm is one of a predefined set. Read the output of npm about that.
3) to answer you question, and do the lazy work, you can put the two commands inside a batch file, set the listening port as a parameter and declare a script section in package.json,
{
"name": "myserver",
"scripts": {
"kill": "killserver.bat"
},
}
then use npm run kill -- 8004,
The port number being of course a parameter in the batch.
Note that this is longer and more complicated than simply calling the batch directly. see https://docs.npmjs.com/cli/run-script, it's useful to understand the possibilities offered by npm.

Related

Nodemon Error: listen EADDRINUSE: address already in use :::3000 [duplicate]

I have a simple server running in node.js using connect:
var server = require('connect').createServer();
//actions...
server.listen(3000);
In my code I have actual handlers, but thats the basic idea. The problem I keep getting is
EADDRINUSE, Address already in use
I receive this error when running my application again after it previously crashed or errors. Since I am not opening a new instance of terminal I close out the process with ctr + z.
I am fairly certain all I have to do is close out the server or connection. I tried calling server.close() in process.on('exit', ...); with no luck.
First, you would want to know which process is using port 3000
sudo lsof -i :3000
this will list all PID listening on this port, once you have the PID you can terminate it with the following:
kill -9 <PID>
where you replace <PID> by the process ID, or the list of process IDs, the previous command output.
You can also go the command line route:
ps aux | grep node
to get the process ids.
Then:
kill -9 PID
Doing the -9 on kill sends a SIGKILL (instead of a SIGTERM).
SIGTERM has been ignored by node for me sometimes.
I hit this on my laptop running win8. this worked.
Run cmd.exe as 'Administrator':
C:\Windows\System32>taskkill /F /IM node.exe
SUCCESS: The process "node.exe" with PID 11008 has been terminated.
process.on('exit', ..) isn't called if the process crashes or is killed. It is only called when the event loop ends, and since server.close() sort of ends the event loop (it still has to wait for currently running stacks here and there) it makes no sense to put that inside the exit event...
On crash, do process.on('uncaughtException', ..) and on kill do process.on('SIGTERM', ..)
That being said, SIGTERM (default kill signal) lets the app clean up, while SIGKILL (immediate termination) won't let the app do anything.
Check the PID i.e. id of process running on port 3000 with below command :
lsof -i tcp:3000
It would output something like following:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 5805 xyz 12u IPv6 63135 0t0 TCP *:3000 (LISTEN)
Now kill the process using :
kill -9 5805
For macOS Monterey(12.0):
Apple introduced some changes for AirPlay on macOS Monterey. Now, it uses 5000 and 7000 ports. If you are using these ports in your project, you need to disable this feature.
System Preferences > Sharing > untick AirPlay Receiver
For macOS Ventura(13.0) and above users:
System Settings > General > disable AirPlay Receiver
I found this solution, try it
Give permission use sudo
sudo pkill node
I usually use
npx kill-port 3000
or on my mac.
killall node
Rewriting #Gerard 's comment in my answer:
Try pkill nodejs or pkill node if on UNIX-like OS.
This will kill the process running the node server running on any port.
Worked for me.
Linux
Run ps and determine the PID of your node process.
Then, run sudo kill PID
Windows
Use tasklist to display the list of running processes:
tasklist /O
Then, kill the node process like so (using the PID obtained from the tasklist command):
taskkill /pid PID
Here is a one liner (replace 3000 with a port or a config variable):
kill $(lsof -t -i:3000)
For windows open Task Manager and find node.exe processes. Kill all of them with End Task.
I was getting this error once and took many of the approaches here.
My issues was that I had two app.listen(3000); calls in the same app.js script. The first app.listen() succeeded where the second threw the error.
Another useful command I came across that helped me debug was sudo fuser -k 3000/tcp which will kill any rogue processes you might have started (some processes may restart, e.g. if run with forever.js, but it was useful for me).
For Visual Studio Noobs like me
You may be running the process in other terminals!
After closing the terminal in Visual Studio, the terminal just disappears.
I manually created a new one thinking that the previous one was destroyed. In reality, every time I was clicking on New Terminal I was actually creating a new one on top of the previous ones.
So I located the first terminal and... Voila, I was running the server there.
Windows by Cmd
1/2. search => write cmd => open node.js command prompt
2/2. Run windows command: taskkill
Ends one or more tasks or processes.
taskkill /f /im node.exe
/f - force ended
/im - Specifies the image name of the process to be terminated.
node.exe - executable file
Windows - Mannualy by Task Manager
This command is the same as going to Task Manager under the details tab & select node tasks (Tidy in my opinion).
And end task
Visual studio
Sometimes there is more than one terminal/task (client/server and so on).
Select and close by ctrl + c.
You may run into scenarios where even killing the thread or process won't actually terminate the app (this happens for me on Linux and Windows every once in a while). Sometimes you might already have an instance running that you didn't close.
As a result of those kinds of circumstances, I prefer to add to my package.json:
"scripts": {
"stop-win": "Taskkill /IM node.exe /F",
"stop-linux": "killall node"
},
I can then call them using:
npm run stop-win
npm run stop-Linux
You can get fancier and make those BIN commands with an argument flag if you want. You can also add those as commands to be executed within a try-catch clause.
FYI, you can kill the process in one command sudo fuser -k 3000/tcp. This can be done for all other ports like 8000, 8080 or 9000 which are commonly used for development.
ps aux | grep node
kill -9 [PID] (provided by above command)
Description:
ps will give the process status, aux provide the list of a: all users processes, u: user own processes, x: all other processes not attached to terminal.
pipe symbol: | will pass the result of ps aux to manipulate further.
grep will search the string provided(node in our case) from the list provided by ps aux.
First find out what is running using:
sudo lsof -nP -i4TCP:3000 | grep LISTEN
You will get something like:
php-fpm 110 root 6u IPv4 0x110e2ba1cc64b26d 0t0 TCP 127.0.0.1:3000 (LISTEN)
php-fpm 274 _www 0u IPv4 0x110e2ba1cc64b26d 0t0 TCP 127.0.0.1:3000 (LISTEN)
php-fpm 275 _www 0u IPv4 0x110e2ba1cc64b26d 0t0 TCP 127.0.0.1:3000 (LISTEN)
Then you can kill the process as followed:
sudo kill 110
Then you will be able to run without getting the listen EADDRINUSE :::3000 errors
Really simply for all OS's ..
npx kill-port 3000
Although your problem is as mentioned above you need to catch the different ways node can exit for example
process.on('uncaughtException', (err, origin) => {
console.log(err);
});
// insert other handlers.
bash$ sudo netstat -ltnp | grep -w ':3000'
- tcp6 0 0 :::4000 :::* LISTEN 31157/node
bash$ kill 31157
PowerShell users:
Taskkill /IM node.exe /F
UI solution For Windows users: I found that the top answers did not work for me, they seemed to be commands for Mac or Linux users. I found a simple solution that didn't require any commands to remember: open Task Manager (ctrl+shift+esc). Look at background processes running. Find anything Node.js and end the task.
After I did this the issue went away for me. As stated in other answers it's background processes that are still running because an error was previously encountered and the regular exit/clean up functions didn't get called, so one way to kill them is to find the process in Task Manager and kill it there. If you ran the process from a terminal/powerShell you can usually use ctrl+c to kill it.
Task Manager (ctrl+alt+del) ->
Processes tab ->
select the "node.exe" process and hit "End Process"
Just in case check if you have added this line multiple times by mistake
app.listen(3000, function() {
console.log('listening on 3000')
});
The above code is for express but just check if you are trying to use the same port twice in your code.
In windows users: open task manager and end task the nodejs.exe file, It works fine.
On Windows, I was getting the following error:
EADDRINUSE: address already in use :::8081.
Followed these steps:
Opened CMD as Admin
Ran the folowing
command netstat -ano|findstr "PID :8081"
got the following processes:
killed it via:
taskkill /pid 43144 /f
On MAC you can do like this:
raghavkhunger#MacBook-Air ~ % lsof -i tcp:8081
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 23722 username 24u IPv6 0xeed16d7ccfdd347 0t0 TCP *:sunproxyadmin (LISTEN)
username#MacBook-Air ~ % kill -9 23722
With due respect to all the answers in the form, I would like to add a point.
I found that when I terminate a node app on error using Ctrl + Z, the very next time when I try to open it got the same error EADDRINUSE.
When I use Ctrl + C to terminate a node app, the next time I opened it, it did without a hitch.
Changing the port number to something other than the one in error solved the issue.
using netstat to get all node processes with the port they are using and then kill the only one you want by PID
netstat -lntp | grep node
you will get all node processes
tcp6 0 0 :::5744 :::* LISTEN 3864/node
and then when you get the PID (3864) just kill the processes by PID
kill -HUP PID
You may use hot-node to prevent your server from crashing/ run-time-errors. Hot-node automatically restarts the nodejs application for you whenever there is a change in the node program[source] / process[running node program].
Install hot-node using npm using the global option:
npm install -g hotnode

Detached child process exits on script exit in node.js

I've followed the instructions in the api docs as far as I can tell. I spawn the process, using the options detached:true, stdio:['ignore','ignore','ignore'], I call unref on the ChildProcess. The ChildProcess has a pid, so I think it was successfully started. I'm trying to start a yeti server from within a grunt task. This code is within an async call, so next proceeds and eventually finishes the task. I use which to getcmd, and its the correct path to the yeti script in /usr/local/bin on Mac OSX 10.9. Port is also defined to an empty port. If I run the same command on the command line it works just fine. After the grunt exits I call ps aux | grep node and ps aux and grep for the logged pid and there is nothing running. Here is the code:
yeti = spawn("" + cmd + " --server --port " + port, [], {
detached: true,
stdio: ['ignore', 'ignore', 'ignore']
});
yeti.unref();
next("Yeti server is running. pid: " + yeti.pid);
Try this:
spawn(cmd, ["--server", "--port", port], {
detached: true,
stdio: ['ignore', 'ignore', 'ignore']
});
I've not seen a single example of spawn where everything was passed as the first argument. I've always seen it used with the first argument being only the command name (i.e. the executable name, or path to executable) and the second argument being an array of strings.
The fact that you were seeing a pid is not indicative of much because on Unix-type systems, the spawn will fork and then exec. The fork can be successful so you see a new pid but the exec fails because the executable's name makes no sense to the OS.
If you found this while investigating why your process exits when you kill the parent, though it's detached, and you're using PM2 :
https://github.com/Unitech/pm2/issues/1036
pm2 uses kill process tree. This kills the entire process tree. Running cli commands with --no-treekill will solve this.
related also: https://github.com/Unitech/PM2/issues/1564

Node: child_process.exec() process continuing after parent process dies

I'm trying to get create a local API service for testing purposes, which involves running a make command in my build system. The code looks like this:
(note: this is in coffeescript)
request = require "request"
child_process = require "child_process"
tsc = require "training_service_connector"
campaign = "happytest"
strategy = campaign
port_number = 54340
service_conf_filename = tsc.writeServiceConfig(strategy, port_number)
exec_callback = (error, stdout, stderr) ->
console.log ('stdout:\n' + stdout + '\nstderr:\n' + stderr + "\nerror:\n" + error)
child_process.exec ("CONFIG=#{service_conf_filename} make run_bidder_service_runner", exec_callback)
# some other stuff
Now, in trying to figure out how to get the rest of the test to run AFTER the API goes up (ugh async), I've been running this code in a REPL. The REPL is buggy, and so I have to use ctrl+Z to kill it a lot. After killing the process, it seems the child process is still running...
lsof -i :54340
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python 52650 max 3u IPv4 20606263 0t0 TCP localhost:54340 (LISTEN)
Now if I try to run it again, I get an error saying the port is already in use. Why doesn't the child process die with the parent?
Different operating systems handle child processes differently. I usually add in handler like this:
['SIGINT', 'SIGHUP', 'SIGTERM'].forEach(function(signal) {
process.addListener(signal, gracefulShutdown);
});
gracefulShutdown should do things like close sockets and quit processes (process.stop())
OH... And I just reread your question. ctrl-z pauses a process, it doesn't kill it. If you use fg or bg, it will bring the process back into the foreground/background. To quick the REPL, use ctrl-c twice.

Stop listening for node.js

When I do:
node server.js
Then my terminal (osx) starts to listen for messages like errors and logs from the node app.
How can I start node without listening?
How can I stop listening programtically from within node.js?
If you are using bash shell (the typical default on a Unix-like operating system such as OS X), you can start it up like this:
node server.js 2>&1 >/dev/null
That directs STDERR and STDOUT to /dev/null.
If you also want to throw the process into the background so you can do other things in the shell, add a & at the end:
node server.js 2>&1 >/dev/null &
Just make sure you know how to bring it back to the foreground (fg command) and/or know how to kill it when you no longer want it running.

Stop node.js program from command line

I have a simple TCP server that listens on a port.
var net = require("net");
var server = net.createServer(function(socket) {
socket.end("Hello!\n");
});
server.listen(7777);
I start it with node server.js and then close it with Ctrl + Z on Mac. When I try to run it again with node server.js I get this error message:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: listen EADDRINUSE
at errnoException (net.js:670:11)
at Array.0 (net.js:771:26)
at EventEmitter._tickCallback (node.js:192:41)
Am I closing the program the wrong way? How can I prevent this from happening?
To end the program, you should be using Ctrl + C. If you do that, it sends SIGINT, which allows the program to end gracefully, unbinding from any ports it is listening on.
See also: https://superuser.com/a/262948/48624
Ctrl+Z suspends it, which means it can still be running.
Ctrl+C will actually kill it.
you can also kill it manually like this:
ps aux | grep node
Find the process ID (second from the left):
kill -9 PROCESS_ID
This may also work
killall node
Or alternatively you can do all of these in one line:
kill -9 $(ps aux | grep '\snode\s' | awk '{print $2}')
You can replace node inside '\snode\s' with any other process name.
Resume and kill the process:
Ctrl+Z suspends it, which means it is still running as a suspended background process.
You are likely now at a terminal prompt...
Give the command fg to resume the process in the foreground.
type Ctrl+C to properly kill it.
Alternatively, you can kill it manually like this:
(NOTE: the following commands may require root, so sudo ... is your friend)
pkill -9 node
or, if you don't have pkill, this may work:
killall node
or perhaps this:
kill $(ps -e | grep node | awk '{print $1}')
sometimes the process will list its own grep, in which case you'll need:
kill $(ps -e | grep dmn | awk '{print $2}')
.
h/t #ruffin from the comments on the question itself. I had the same issue and his comment helped me solve it myself.
If you are running Node.js interactively (the REPL):
Ctrl + C will take back you to > prompt then type:
process.exit()
or just use Ctrl + D.
you can type .exit to quit node js REPL
$ sudo killall node in another terminal works on mac, while killall node not working:
$ killall node
No matching processes belonging to you were found
on linux try: pkill node
on windows:
Taskkill /IM node.exe /F
or
from subprocess import call
call(['taskkill', '/IM', 'node.exe', '/F'])
you can work following command to be specific in localserver kill(here: 8000)
http://localhost:8000/ kill PID(processId):
$:lsof -i tcp:8000
It will give you following groups of TCPs:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 21521 ubuntu 12u IPv6 345668 0t0 TCP *:8000 (LISTEN)
$:kill -9 21521
It will kill processId corresponding to TCP*:8000
You can use fuser to get what you want to be done.
In order to obtain the process ids of the tasks running on a port you can do:
fuser <<target_port>>/tcp
Let's say the port is 8888, the command becomes:
fuser 8888/tcp
And to kill a process that is running on a port, simply add -k switch.
fuser <<target_port>>/tcp -k
Example (port is 8888):
fuser 8888/tcp -k
That's it! It will close the process listening on the port.
I usually do this before running my server application.
For MacOS
Open terminal
Run the below code and hit enter
sudo kill $(sudo lsof -t -i:4200)
Though this is a late answer, I found this from NodeJS docs:
The 'exit' event is emitted when the REPL is exited either by receiving the .exit command as input, the user pressing <ctrl>-C twice to signal SIGINT, or by pressing <ctrl>-D to signal 'end' on the input stream. The listener callback is invoked without any arguments.
So to summarize you can exit by:
Typing .exit in nodejs REPL.
Pressing <ctrl>-C twice.
pressing <ctrl>-D.
process.exit(0) meaning a natural exit from REPL. If you want to return any other status you can return a non zero number.
process.kill(process.pid) is the way to kill using nodejs api from within your code or from REPL.
If you want to stop your server with npm stop or something like this. You can write the code that kill your server process as:
require('child_process').exec(`kill -9 ${pid}`)
Check this link for the detail:
https://gist.github.com/dominhhai/aa7f3314ad27e2c50fd5
I'm adding this answer because for many projects with production deployments, we have scripts that stop these processes so we don't have to.
A clean way to manage your Node Server processes is using the forever package (from NPM).
Example:
Install Forever
npm install forever -g
Run Node Server
forever start -al ./logs/forever.log -ao ./logs/out.log -ae ./logs/err.log server.js
Result:
info: Forever processing file: server.js
Shutdown Node Server
forever stop server.js
Result
info: Forever stopped process:
uid command script forever pid id logfile uptime
[0] sBSj "/usr/bin/nodejs/node" ~/path/to/your/project/server.js 23084 13176 ~/.forever/forever.log 0:0:0:0.247
This will cleanly shutdown your Server application.
I ran into an issue where I have multiple node servers running, and I want to just kill one of them and redeploy it from a script.
Note: This example is in a bash shell on Mac.
To do so I make sure to make my node call as specific as possible. For example rather than calling node server.js from the apps directory, I call node app_name_1/app/server.js
Then I can kill it using:
kill -9 $(ps aux | grep 'node\ app_name_1/app/server.js' | awk '{print $2}')
This will only kill the node process running app_name_1/app/server.js.
If you ran node app_name_2/app/server.js this node process will continue to run.
If you decide you want to kill them all you can use killall node as others have mentioned.
Late answer but on windows, opening up the task manager with CTRL+ALT+DEL then killing Node.js processes will solve this error.
My use case: on MacOS, run/rerun multiple node servers on different ports from a script
run: "cd $PATH1 && node server1.js & cd $PATH2 && node server2.js & ..."
stop1: "kill -9 $(lsof -nP -i4TCP:$PORT1 | grep LISTEN | awk '{print $2}')"
stop2, stop3...
rerun: "stop1 & stop2 & ... & stopN ; run
for more info about finding a process by a port: Who is listening on a given TCP port on Mac OS X?
For windows first search the PID with your port number
netstat -ano | findStr "portNumber"
After that, kill the task, make sure you are in root of your "c" drive
And the command will be taskkill /F /PID your pid
if you are using VS Code and terminal select node from the right side dropdown first and then do Ctrl + C. Then It will work
Press y when you are prompted.
Thanks

Resources