# How to terminate a Node.js application

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 30, 2021, updated Oct 3, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-terminate-app

> A quick guide to learn how to programmatically 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.

```javascript
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:

```javascript
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](https://nodejs.org/api/process.html#process_exit_codes) 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:

```javascript
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:

```javascript
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:

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