lgc_ustc lgc_ustc - 1 year ago 185
Node.js Question

Cleaning up in node.js before exit

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:

description "node.js"

# Start the job
start on runlevel [2345]

# Stop the job
stop on runlevel [016]

# Restart the process if it dies

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?

Answer Source

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.


// 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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download