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?
$ sudo killall node
in another terminal works on mac, whilekillall node
not working: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 (fromNPM
).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.
Though this is a late answer, I found this from NodeJS docs:
So to summarize you can exit by:
.exit
in nodejs REPL.<ctrl>-C
twice.<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.on linux try:
pkill node
on windows:
or
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 callingnode server.js
from the apps directory, I callnode 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.you can type
.exit
to quit node js REPL