Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js shutdown hook

In Express.js, is there someway of setting a callback function to be executed when the application shuts down?

like image 256
William Avatar asked Dec 14 '11 18:12

William


People also ask

What is graceful shutdown Express?

Procedure of Graceful Shutdown: For this purpose, a SIGTERM (the program manager sends it ) signal is sent to the application that tells it that it is going to be killed. After getting this signal, the app stops accepting the new requests, by letting the load balancer know that is not going to accept any new requests.

How do I stop express JS server?

log("server started at port 3000"); }); Once the server starts listening, it will never stop until the interrupt signal or a code error crash the program. To stop your NodeJS server from running, you can use the ctrl+C shortcut which sends the interrupt signal to the Terminal where you start the server.

Why was graceful shut down?

A graceful shutdown is when a computer is turned off by software function and the operating system (OS) is allowed to perform its tasks of safely shutting down processes and closing connections. A hard shutdown is when the computer is forcibly shut down by interruption of power.


2 Answers

You could use the node.js core process 'exit' event like so:

process.on('exit', function() {   // Add shutdown logic here. }); 

Of course, the main event loop will stop running after the exit function returns so you can't schedule any timers or callbacks from within that function (e.g. any I/O must be synchronous).

like image 50
maerics Avatar answered Oct 02 '22 18:10

maerics


There is process.on('exit', callback):

process.on('exit', function () {   console.log('About to exit.'); }); 
like image 25
alessioalex Avatar answered Oct 02 '22 19:10

alessioalex