Command for Continuous Running Your Server

What is forever?

Forever is an npm module that ensures a Node.js script continuously runs in the background on the server. It's a helpful CLI tool for the production environment because it helps manage the Node applications and their processes.

In this article, we will learn how to set up forever with our Node application, as well as learn some important forever commands.

Installing forever

Forever can be used in two ways: with the forever CLI tool and with forever-monitor. The forever-monitor tool can be used to run an application with forever using code. We will see forever-monitor in action later in this article.

To use forever, we need to install it globally:

npm i -g forever        

Running a script with forever

Running a script with forever is simple. First, use the following command:

forever start app.js        

Note that app.js is the name of the script. We can also add a -a flag with the above command. This flag will ensure that log files get appended to the default log file located at forever's default log file location. There are many other flags available that can be appended to the forever command.

We can also run multiple scripts at once by separating the script names with spaces. Here is an example:

forever start app.js index.js        

When you start the processes using the above commands, you'll receive some warnings and information about the file that it is processing.

After you start the script, you can list all the running processes with the list command, like so:

forever list        

Here's what the output looks like:

Forever List Output

In this output, we can see important details, such as the id of the process, the script name and location, the log file location, uptime duration, and more.

Starting and stopping scripts with forever commands

When we work in production servers, our priority is to run the script uninterruptedly even if some error occurs. Forever does this for us. Even if some error occurs, forever will restart the script for us. But there may be also cases, when we need to stop a script, maybe we need to push a new change or there is no use of the script, in such cases, to start or stop the process, the index ID can be really handy.

In the above image, you can see [0] in front of the uid. This is the index number of the script and can be used to kill or stop a process.

To stop a running script from the CLI, use stop, followed by any of the index id, script name, the uid, or the process ID (pid).

forever stop 0 // or forever stop index.js // or forever stop ehbz // or forever stop 8196        

It's also possible to assign a unique name when starting a process. Using the tag --uid newapp will name the process newapp.

forever start --uid newapp index.js        

We can also stop the process like this:

forever stop newapp        

If multiple processes are running and you want to stop all of them at once, you can also use the command stopall, like so:

forever stopall        

Restarting a process with forever is similar to stopping it. We replace the keyword stop with restart:

forever restart 0        

We can use any index id, script name, the uid, or pid to restart a process. To restart all processes at once, we use restartall.

forever restartall        

Configuring and executing a JSON file with forever

Up to this point, we have used CLI commands to run and manage the Node script. But with forever, we can also configure a JSON file where we can define all the necessary details and execute the JSON file. Let's see an example.

{   "uid": "app",   "append": true,   "watch": true,   "script": "./index.js",   "logFile": "./logs/forever.log",   "outFile": "./logs/out.log",   "errFile": "./logs/error.log" }        

Here, the uid is the unique name we are giving to the process. In our case, we are naming it app. The append flag does the same as -a flag; it appends logs. The watch flag watches for file changes.

Script is the script that we are running, and the logFile, outFile, and errFile are the location of the log file, output file, and error log file.

Multiple processes can also be set up into a single JSON file.

[   {     // App1     "uid": "app1",     "append": true,     "watch": true,     "script": "index.js",     "sourceDir": "/home/nemo/app1"   },   {     // App2     "uid": "app2",     "append": true,     "script": "index.js",     "sourceDir": "/home/nemo/app2",     "args": ["--port", "4000"]   } ]        

We have defined two objects, App1 and App2, into a single array in a JSON file here. Running this single JSON file will run multiple processes.

Now, let's talk about the forever-monitor module.

Using forever without CLI

The forever-monitor module helps run processes programmatically without using the CLI. Let's assume we have a basic Express server that we want to run with forever-monitor. Here is the code for the server.

const express = require('express'); const app = express();  app.get('/', (req, res) => {   res.send('Hello World!'); });  const PORT = process.env.PORT || 3000;  app.listen(PORT, () => {   console.log(`Server is running on port ${PORT}`); });        

We have an index route that will show Hello World when we hit it. Now, to use forever-monitor package, we first have to install the dependency with npm i forever-monitor.

We'll also have to create a separate file and define the options in it. In this example, I'll name this file fm.js. In it, we have to import the forever-monitor module first. After importing the module, we'll set up the options to run our app. For this tutorial, we'll keep this very simple. Here is the code.

const forever = require('forever-monitor');  const child = new forever.Monitor('index.js', {   max: 3,   silent: false,   uid: 'index', });  child.on('exit', function () {   console.log('app.js has exited after 3 restarts'); });  child.start();        

The child variable holds the constructor created from the forever.Monitor method. This constructor takes in two parameters, the file name that we want to run, and an object with options. I've provided three options here.

The max: 3 key-value pair represents the maximum number of retries. If the silent flag is true, it silences the output from stdout and stderr in the parent process. The uid flag sets a name for the process.

In the child.on method, we are listening for an event called exit. When the event is triggered, we console log a message. Essentially, the process exits when the maximum number of retries is reached.

Finally, we start the process with child.start(). Now, running the script in the terminal with node fm.js will start our process.

This is how we can run scripts using forever without using the CLI.

Conclusion

Forever is a simple and helpful tool that enables devs to run Node scripts continuously. But it is also worth noting that, because of its simplicity, it lacks some features, so try it out and decide if forever or another tool like PM2 would best suit your use case. Happy hacking.

200's only Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you're interested in ensuring requests to the backend or third party services are successful, try LogRocket. LogRocket Network Request Monitoringhttps://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.

cobbhisaing.blogspot.com

Source: https://blog.logrocket.com/running-node-js-scripts-continuously-forever/

0 Response to "Command for Continuous Running Your Server"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel