Before exit scripts in Node.js

Ever wonder how to do something just before a Node.js process ends? Safely close connections, clean up caches, or log your app’s status somewhere? With this script you can do it.

See it in action on RunKit

Source code

// Add pre-exit script
process.on( 'exit', code => {
  console.log( `Whoa! Exit code ${code}, cleaning up...` );
  // i.e. close database

// Add another for fun
process.on( 'exit', code => {
  if ( code > 0 ) {
    console.log( 'Hmm something went wrong' );
  } else {
    console.log( 'And done!' );
} );

console.log( 'App ready.' );
console.log( 'Doing app stuff...' );

2018-08-14 – Reduced code to essence


Leave a Reply

Your email address will not be published. Required fields are marked *