81

I'm reading through the excellent online book http://nodebeginner.org/ and trying out the simple code

var http = require("http");

function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888); 

Now I didn't know (and I still don't know!) how to shut down node.js gracefully, so I just went ctrl+z. Now each time I try to run node server.js I get the following error messages.

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: EADDRINUSE, Address already in use
    at Server._doListen (net.js:1100:5)
    at net.js:1071:14
    at Object.lookup (dns.js:153:45)
    at Server.listen (net.js:1065:20)
    at Object.<anonymous> (/Users/Bob/server.js:7:4)
    at Module._compile (module.js:402:26)
    at Object..js (module.js:408:10)
    at Module.load (module.js:334:31)
    at Function._load (module.js:293:12)
    at Array.<anonymous> (module.js:421:10)

So, two questions:

1) How do I shut down node.js gracefully?

2) How do I repair the mess I've created?

Randomblue
  • 112,777
  • 145
  • 353
  • 547
  • Check out the following question [Graceful shutdown of a node.JS HTTP server](http://stackoverflow.com/questions/5263716/graceful-shutdown-of-a-node-js-http-server/). – jdavies Aug 05 '11 at 15:38
  • 19
    FYI, ctrl+Z means "pause". After you've paused a process, you can type `fg` (to resume it normally), or `bg` (to resume it in the background). – s4y Sep 03 '11 at 19:25
  • 1
    typing `fg` from bash worked great for me on centOS6 !! much, much easier than accepted answer :DD +2 sir, if i could – RozzA Mar 03 '14 at 07:40
  • this is much easier. – Raaz Mar 02 '15 at 08:04

5 Answers5

130

I currently use Node's event system to respond to signals. Here's how I use the Ctrl-C (SIGINT) signal in a program:

process.on( 'SIGINT', function() {
  console.log( "\nGracefully shutting down from SIGINT (Ctrl-C)" );
  // some other closing procedures go here
  process.exit( );
})

You were getting the 'Address in Use' error because Ctrl-Z doesn't kill the program; it just suspends the process on a unix-like operating system and the node program you placed in the background was still bound to that port.

On Unix-like systems, [Control+Z] is the most common default keyboard mapping for the key sequence that suspends a process (SIGTSTP).[3] When entered by a user at their computer terminal, the currently running foreground process is sent a SIGTSTP signal, which generally causes the process to suspend its execution. The user can later continue the process execution by typing the command 'fg' (short for foreground) or by typing 'bg' (short for background) and furthermore typing the command 'disown' to separate the background process from the terminal.1

You would need to kill your processes by doing a kill <pid> or 'killall -9 node' or the like.

l0b0
  • 55,365
  • 30
  • 138
  • 223
EhevuTov
  • 20,205
  • 16
  • 66
  • 71
  • 3
    `killall -9` is a bit drastic; I'd not go there unless `killall -INT` or just plain `killall` don't work. – icktoofay Apr 15 '13 at 02:08
  • 3
    In addition to SIGINT, one also might want to listen for SIGTERM and SIGHUP , and have an on uncaughtException and an onexit. Signal 9 (SIGKILL) can't be listened for, if you use that, its dead. – Paul Jul 15 '13 at 10:42
  • What would be the example code if you wanted all current requests to be flushed and not accept any new requests before you gracefully shutdown the node process? – CMCDragonkai Jun 23 '14 at 05:00
  • 1
    getting back into the running process with 'fg' was perfect. thank you sir +1 a much better option than kill – RozzA Nov 06 '14 at 05:06
55
  1. Use Ctrl+C to exit the node process gracefully

  2. To clean up the mess depends on your platform, but basically you need to find the remains of the process in which node was running and kill it.

    For example, on Unix: ps -ax | grep node will give you an entry like:

    1039 ttys000    0:00.11 node index.js
    

    where index.js is the name of your node file.

    In this example, 1039 is the process id (yours will be different), so kill -9 1039 will end it, and you'll be able to bind to the port again.

Oliver Salzburg
  • 21,652
  • 20
  • 93
  • 138
avstrallen
  • 986
  • 9
  • 9
  • 2
    note that ctrl+c issues a SIGINT which by default stops the process immediately. `kill` sends the SIGTERM signal which is commonly used to start a more graceful shutdown. [unix signals](http://en.wikipedia.org/wiki/Unix_signals) – bhurlow Feb 14 '14 at 00:08
  • 4
    `SIGHUP (1)`, `SIGINT (2`), `SIGTERM (3)` ... `SIGKILL (9)`. Their numeric value is directly proportional to their severity, and inversely proportion to the chance of a "graceful shutdown" – application willing. `kill -9` a.k.a. `kill -KILL`, which will terminate with prejudice (process is simply ended without warning). `kill -TERM` will kindly request a process quits immediately, `kill -INT` will terminate simple things like **cat**, `kill -HUP` sometimes causes a process to reload it's configuration. `kill -TERM` FTW. – Orwellophile May 17 '15 at 13:04
  • @BHBH `SIGINT` is also commonly understood to request a graceful exit. The resource you linked mentioned `SIGTERM` is nearly identical to it. [Many discussions](http://stackoverflow.com/q/4042201) explore the differences. @Orwellophile neither `SIGINT` nor any other signal discriminate based on the "simplicity" of processes or the programs they run; you can safely collapse your descriptions of `SIGTERM` and `SIGINT` into one, lest you risk confusing your readers. – tne Aug 09 '16 at 19:11
22

As node.js is an event-driven runtime the most graceful exit is to exhaust the queue of pending events. When the event queue is empty the process will end. You can ensure the event queue is drained by doing things such as clearing any interval timers that are set and by closing down any servers with open socket connections. It gets trickier when using 3rd party modules because you are at the mercy of whether the module author has taken care to gracefully drain the pending events it created. This might not be the most practical way to exit a node.js process as you will spend a lot of effort tracking down 'leaked' pending events, but it is the most graceful I think.

jkingyens
  • 801
  • 7
  • 9
7

Type either

process.exit()

or

.exit

to exit node gracefully.

Hitting Control + C twice will force an exit.

nbro
  • 15,395
  • 32
  • 113
  • 196
Vietnhi Phuvan
  • 2,704
  • 2
  • 25
  • 25
1

1) How do I shut down node.js gracefully?

Listening for a SIGINT signal. On Windows you need to listen for a ctrl-c with the readline module.

I've written my own solution to provide an application a graceful shutdown and the usage of domains: grace. It's worth to have a look.

Gabriel Llamas
  • 18,244
  • 26
  • 87
  • 112