359

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?

Eleeist
  • 6,891
  • 10
  • 50
  • 77
  • 5
    Probably worth adding that [Ctrl-Z *suspends*](http://superuser.com/a/262948) a command on *NIX, and doesn't close it. If you type `fg` after Ctrl-Z, you'll be back where you left off. So your earlier node is still running. Watch out if you're doing this for other commands too! – ruffin Nov 11 '16 at 16:37
  • 4
    @ruffin this should be an answer. If you've done the `Ctrl+Z` action, a proper methodology could be `fg` to revive the process, and then `Ctrl+C` to kill it proper. – Metagrapher May 26 '17 at 21:18

19 Answers19

422

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

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
  • 29
    `Ctrl + C` does not work for me. Only `^C` gets typed into the console, and program does not exits. – Eleeist May 09 '12 at 19:21
  • 2
    @Eleeist, What are you using as a terminal? It works great for me. – Brad May 09 '12 at 19:22
  • I am using default Mac OS X Terminal application. – Eleeist May 09 '12 at 19:23
  • 4
    @Eleeist, You've probably remapped your keys or something. `Ctrl+C` works fine. In any case, that's a separate issue from your real problem. You should post a "Ctrl+C doesn't work" question over at SuperUser.com. – Brad May 09 '12 at 19:31
  • @Jerry What terminal are you using? No issue like that here on my Mac. – Brad Nov 20 '13 at 22:23
  • @Brad Ah, heck. After going and testing I realized that it's one of my other servers that requires a double-tap to kill. Sorry for the misinformation. Deleted my previous comment. – Jerry Nov 21 '13 at 01:11
  • Is there an alternate, more definite way to do it, even un-gracefully? Every once in a while I get that EADDRINUSE error even through nothing is running, and I just have to wait for some time before I can run –  Jul 10 '14 at 19:40
  • 1
    @jt0dd You could always `kill -9`, but I wouldn't. Are you actually sure your application is still the one keeping ports open? I've never had that problem. As soon as my application ends, the connections are always immediately terminated. I would use netstat to determine if your app or something else is lingering on that port. – Brad Jul 10 '14 at 19:52
  • @Brad It's something to do with PM2. I use PM2 to keep the apps running and manage memory used, and that was keeping the port open after closure of the process. –  Jul 10 '14 at 22:18
  • 1
    I faced to this problem when I was using keyboard type on other language. Be sure your mac input language is English – Fa.Shapouri Dec 28 '16 at 17:07
  • Thank you I had no idea you could do this and it will save me so much time. – Melkor Apr 21 '17 at 16:15
  • @Melkor Out of curiosity, how had you been stopping your applications? – Brad Apr 21 '17 at 17:37
  • @Brad close cmd, open cmd, copy paste the file location, cd the file location, npm start. – Melkor Apr 21 '17 at 17:41
  • Had written some random stuff like exit or quit, ctrl-C did not work, but surprinsingly typing ^C then enter worked. – Ambroise Rabier Dec 10 '18 at 22:05
  • 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 thank – MindRoasterMir Apr 11 '20 at 12:42
  • the only thing that worked in VS code is right client and choose "kill terminal" which doesn't have a shortcut – Ali123 Apr 20 '20 at 19:15
403

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
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
  • ctrl+c will work but none of these command will work for me. I don't know why ? And I'm looking for command line solution – angry kiwi Aug 26 '12 at 03:59
  • 11
    Be careful with killall node, you might kill process you wouldn't want to kill if they match "node" – Samuel Bolduc Jul 17 '13 at 17:21
  • 5
    you may want to move up `killall node`in your answer since that is really the easiest and most reliable option (as long as you're ok with killing all instances) – Boern Jan 24 '16 at 14:42
  • 6
    'killall' is not recognized as an internal or external command, operable program or batch file. Am i missing something? – Ayyash Nov 08 '16 at 08:42
  • Same here... No answer? It says 'killall' is not recognized. None of the other commands work either. Do I need to restart my computer or what? – Methodician Feb 01 '17 at 02:13
  • What OS and version are you on? Mac OS 10.14 has killall. – geoidesic Oct 20 '18 at 12:01
  • I exited ssh session keeping the node server running and when logged in again i had to use kill -9 PROCESS_ID option. – Ifta Nov 13 '18 at 04:45
  • what is the purpose of using -9 there ? – Eve Feb 09 '22 at 03:48
41

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.

Hamid Tavakoli
  • 4,567
  • 1
  • 33
  • 34
35

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.

Community
  • 1
  • 1
Metagrapher
  • 8,602
  • 1
  • 24
  • 31
23

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.

Brad
  • 159,648
  • 54
  • 349
  • 530
sr77in
  • 307
  • 2
  • 13
22

you can type .exit to quit node js REPL

sunny1304
  • 1,684
  • 3
  • 17
  • 30
20

on linux try: pkill node

on windows:

Taskkill /IM node.exe /F

or

from subprocess import call

call(['taskkill', '/IM', 'node.exe', '/F'])
Jason
  • 1,974
  • 24
  • 19
  • Taskkill /IM node.exe /F worked for me on windows10 with node.js running on a usb. I am using pm2 to start/stop but this doesn't stop node.js which means you can't safely eject the usb as node.js still runs after pm2 stop. Your solution is perfect! – user2677034 Jan 01 '22 at 20:02
17

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

$ killall node
No matching processes belonging to you were found
Maxim Yefremov
  • 13,671
  • 27
  • 117
  • 166
13

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

Ank_247shbm
  • 512
  • 7
  • 17
9

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.

Vikram Bankar
  • 386
  • 4
  • 4
8

For MacOS

  1. Open terminal
  2. Run the below code and hit enter

     sudo kill $(sudo lsof -t -i:4200)
    
6

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.
randominstanceOfLivingThing
  • 16,873
  • 13
  • 49
  • 72
5

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

BigEgg
  • 101
  • 2
  • 5
5

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.

Decoded
  • 1,057
  • 13
  • 17
3

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.

bapin93
  • 162
  • 10
2

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

rmolinamir
  • 1,121
  • 14
  • 15
1

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?

Edan Chetrit
  • 4,713
  • 2
  • 20
  • 20
1

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 enter image description here And the command will be taskkill /F /PID your pid

gem007bd
  • 1,085
  • 13
  • 11
1

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

enter image description here

Press y when you are prompted.

enter image description here

Thanks

MindRoasterMir
  • 324
  • 1
  • 2
  • 18