0

There has been lots of questions asking: how do we exit and what exactly does it do in node js: by using the process.exit() command. But when and why would you need to exit?

How I understand this currently is node/nodemon app.js starts up a process with the server in which our website runs. So when and why would we ever need to shut it down in production?

I came across this after seeing how to close MongdoDB connection on this SO article(accepted answer, comment section): Mongoose Close Connection

LeggoMaEggo
  • 512
  • 1
  • 9
  • 24

1 Answers1

3

process.exit() is somewhat needed for cloud services such as Heroku.

If you host your application on a service such as Heroku then the application will restart at least once per day. This is called cycling. When the Heroku dyno cycles it will send SIGTERM to the application, which, for example, can be handled in the following way:

process.on('SIGTERM', gracefulShutdown);

function gracefulShutdown() {
  mongoose.connection.close(() => {
    console.log('Shutting down');
    process.exit(0);
  });
}

When the application is sigtermed we want to gracefully close the database connection before we proceed with shutting down. We stop the default behavior by listening to the SIGTERM event, but we still have to do what SIGTERM is supposed to do, which is stopping the process. Heroku will restart the application afterward.

Mika Sundland
  • 18,120
  • 16
  • 38
  • 50