Stop node.js program from command line

2019-01-16 00:19发布

问题:

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?

回答1:

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



回答2:

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


回答3:

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.



回答4:

you can type .exit to quit node js REPL



回答5:

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.



回答6:

$ sudo killall node in another terminal works on mac, while killall node not working:

$ killall node
No matching processes belonging to you were found


回答7:

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...

  1. Give the command fg to resume the process in the foreground.

  2. 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.



回答8:

on linux try: pkill node

on windows:

Taskkill /IM node.exe /F

or

from subprocess import call

call(['taskkill', '/IM', 'node.exe', '/F'])


回答9:

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:

  1. Typing .exit in nodejs REPL.
  2. Pressing <ctrl>-C twice.
  3. pressing <ctrl>-D.
  4. process.exit(0) meaning a natural exit from REPL. If you want to return any other status you can return a non zero number.
  5. process.kill(process.pid) is the way to kill using nodejs api from within your code or from REPL.


回答10:

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.



回答11:

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



回答12:

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.



回答13:

Late answer but on windows, opening up the task manager with CTRL+ALT+DEL then killing Node.js processes will solve this error.



回答14:

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?