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', function () {
    console.log('Parent SIGTERM detected (kill)');
    // exit cleanly
    process.exit(0);
});

When you run your code now, and press Ctrl+C, the output will look like this:
...
^C
Gracefully shutting down from  SIGINT (Crtl-C)
Exiting ...
bye

Just a reminder - when event exit happens, you cannot use any callbacks since they will not be executed:
process.on('exit', function() {
  setTimeout(function() {
    console.log('This will not run!');
  }, 0);
  console.log('About to exit.');
});



More on topic: Running node.js application in port 80

Comments

Popular posts from this blog

Stubbing and Mocking Static Methods with PHPUnit

Enable HTTP/2 Support in AWS ELB

How To Attach Your EBS volume to multiple EC2 instances