We have a node.js/express/socket.io server, managed by Upstart. The server is stopped by running this command in bash: 'stop nodejs', where nodejs is an Upstart script with the following content:
#!upstart
description "node.js"
# Start the job
start on runlevel [2345]
# Stop the job
stop on runlevel [016]
# Restart the process if it dies
respawn
script
cd /var/www/node_server/
exec /usr/local/node/bin/node /var/www/node_server/chatserver.js >> /var/www/node_server/chatserver.log 2>&1
end script
post-start script
# Optionally put a script here that will notify you node has (re)started
# /root/bin/hoptoad.sh "node.js has started!"
end script
We'd like to perform some cleanup work right before the server is stopped like mentioned above. We have tried both process.on('exit' ... ) and process.on('SIGINT' ... ), to no avail.
How to call a callback right before the server is stopped?
After diving into the docs, upstart fires a SIGTERM signal to terminate the program:
http://upstart.ubuntu.com/cookbook/#stopping-a-job
hence you listen to this signal using node: https://nodejs.org/api/process.html#process_signal_events
SIGTERM is not supported on Windows, it can be listened on.
short example:
// Begin reading from stdin so the process does not exit.
process.stdin.resume();
// listen to the event
process.on('SIGTERM', () => {
console.log('some cleanup here');
});
This should do the job.
Additionally, you have a pre-stop upstart event that you can close node with manually before closing the service to ensure a proper closing of node.
http://upstart.ubuntu.com/cookbook/#pre-stop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With