4 service snippets
gracefully closing node.js applications via signal handling
To make your node.js application gracefully respond to shutdown signals, use process.on(SIGNAL,HANDLER)
.
For example, to respond to SIGINT
(typically Ctrl-c), you can use:
process.on( "SIGINT", function() {
console.log('CLOSING [SIGINT]');
process.exit();
} );
Note that without the process.exit()
, the program will not be shutdown. (This is you chance to override or "trap" the signal.)
Some common examples (in CoffeeScript):
process.on 'SIGHUP', ()->console.log('CLOSING [SIGHUP]'); process.exit()
process.on 'SIGINT', ()->console.log('CLOSING [SIGINT]'); process.exit()
process.on 'SIGQUIT', ()->console.log('CLOSING [SIGQUIT]'); process.exit()
process.on 'SIGABRT', ()->console.log('CLOSING [SIGABRT]'); process.exit()
process.on 'SIGTERM', ()->console.log('CLOSING [SIGTERM]'); process.exit()
PS: On Linux (and similar) you can enter kill -l
on the command line to see a list of possible signals, and kill -N PID
to send signal N to the process with process ID PID.
Shell script for service-like CoffeeScript/Node.js apps using forever
This is an example of a (bash) shell script that uses the forever module to start and stop a CoffeeScript application as if it were a service.
(Also at rodw/coffee-as-a-service-via-forever.sh.)
Cheat Sheet for Linux Run Levels
"Standard" Linux uses the following run levels:
- Run Level 0 is halt (shutdown).
- Run Level 1 is single-user mode.
- Run Level 2 is multi-user mode (without networking)
- Run Level 3 is multi-user mode (with networking). This is the normal "terminal" mode. (I.e., before the display manager is run).
- Run Level 4 is undefined.
- Run Level 5 is multi-usermode with a GUI display manager (X11).
- Run Level 6 is reboot.
In Debian and its derivatives run levels 2 thru 5 are the same: multi-user mode with networking, and with a display manager if available.
- Run Level 0 is halt (shutdown).
- Run Level 1 is single-user mode.
- Run Level 2-5 is multi-user mode with networking and a GUI display manager when available.
- Run Level 6 is reboot.
Debian also adds Run Level S, which is executed when the system first boots.
Also see Wikipedia's article on run levels.