How to restart Node.js application when uncaught exception happen ?
In this article, we are going to learn, about restarting a Node.js application when an uncaught exception happens. For this, we are going to use the pm2 module.
Approach: Let’s see the approach step by step:
- Step 1: Install the pm2 module and use it to start the server.
- Step 2: When an uncaught exception happens, then execute the command process.exit() to stop the server.
- Step 3: Then, pm2 module will automatically start the server again.
process.exit() stop the server and pm2 force it to start. In this way, the server will restart.
Implementation: Below is the step-by-step implementation of the above approach.
Step 1: Initializes NPM: Create and Locate your project folder in the terminal & type the command
npm init -y
It initializes our node application & makes a package.json file.
Step 2: Install Dependencies: Locate your root project directory into the terminal and type the command
npm install express pm2
To install express and pm2 as dependencies inside your project
Step 3: Creating a list of products: Let’s create an array of products and set it to constant products.
const products = [];
Step 4: Creating Routes for the home page and the products page: Let’s create two routes so that users can access the home page and the products page.
app.get('/', (req, res) => { res.send('Hello Beginner!'); }); app.get('/products', (req, res) => { if (products.length === 0) { res.send('No products found!'); process.exit(); } else { res.json(products); } });
Inside the product route, we use process.exit() method to stop the server.
Complete Code:
Javascript
const express = require( 'express' ); const app = express(); const products = []; app.get( '/' , (req, res) => { res.send( 'Hello Beginner!' ); }); app.get( '/products' , (req, res) => { if (products.length === 0) { res.send( 'No products found!' ); process.exit(); } else { res.json(products); } }); app.listen(3000, ()=>{ console.log( 'listening on port 3000' ); }); |
Steps to run the application: Inside the terminal type the command to run your script ‘app.js’ with pm2.
pm2 start app.js
Output:
Contact Us