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\"
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
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.
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:
.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.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.
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
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.
(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.