Gracefully Exiting node.js / Express Web Application

Running node.js application is easy, but how do you close the application gracefully without errors? Typically you run the app in command line while developing, e.g. node app.js - press Ctrl+C or Command+C to stop running process. If you have sent your application into the background, you can execute kill <pid> command; you can get process ID <pid> with ps aux | grep node . This will kill your app, but if you want to end your application and close all the resources, you can use node.js process events: // Execute commands in clean exit process.on('exit', function () { console.log('Exiting ...'); if (null != db) { db.close(); } // close other resources here console.log('bye'); }); // happens when you press Ctrl+C process.on('SIGINT', function () { console.log( '\nGracefully shutting down from SIGINT (Crtl-C)' ); process.exit(); }); // usually called with kill process.on('SIGTERM', func...