How to terminate a Node.js application

There are multiple ways to terminate a Node.js application. If the application is running in a console, you use the CTRL + C to close the application.

However, to programmatically terminate a Node.js application, you need to use the exit() method from the process module.

The process object is a built-in module that provides information about the current Node.js process. It also allows you to manage the current Node.js process directly from the application.

process.exit([code]);

The process.exit() method tells Node.js to terminate the process immediately. It means that any pending callback, any network request still in execution, any database request in progress, or any filesystem access will be ungracefully terminated.

You can also pass an integer value to process.exit() that sends an exit code to the operating system:

process.exit(5)

By default, the exit code is 0, which means success. The exit code 5 means "Fatal Error", meaning Node.js encounters an unrecoverable error.

Each exit code has a specific meaning that you can use in your application to let the operating system knows why the application was terminated.

Alternatively, you could also set the exit code by using the process.exitCode property:

process.exitCode = 5

What if you want to gracefully terminate the process? In this case, you need to send the process a SIGTERM signal and then listen for this event using the process event handler.

Here is an example of a Node.js HTTP server that listens for the SIGTERM event to gracefully close the server:

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello world!')
})

const server = app.listen(3500, () => console.log(`Server started!`))

process.on('SIGTERM', () => {
  server.close(() => console.log(`Server closed!`))
})

The process.kill() method can be used to send a SIGTERM signal to the current Node.js process:

process.kill(process.pid, "SIGTERM");

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.