Running Node.js scripts continuously using forever
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