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.