a blog for those who code

Thursday, 28 August 2014

Use of Forever in Nodejs

In this post we will show you what is the use of Forever in Nodejs. Forever is a tool that restarts your application if it crashes.

Suppose if you don't want your application to be down even if it crashes, you can use forever. It can be used using command line to restart your application or you can incorporate it as part of your application.

How to use forever using command line

At first you need to install Forever globally like npm install forever -g
then you can use forever command to start your application like
forever [action] [options] SCRIPT [script-options]

where important actions are
start - to start a script
stop - to stop a script
stopall - stop all running forever scripts
restart - restart the script
restartall - restart all running forever scripts
logs - list all logs (all forever process)
cleanlogs - delete all forever log files
list - list all running forever scripts
config - lists all user configuration

where options are like
-m MAX - run script MAX times
-l LOGFILE - logs the output to LOGFILE
-c COMMAND - COMMAND to execute
-s - run the child script silently
-w - watch the file changes

If you want to know the options or actions available you can check using forever --help

$ forever -m 10 -a -l logFile.log -e errorFile.log serv.js

The above command starts a script serv.js, and specifies name for log file and error log file. Now, if any point of time the script crashes, Forever restarts it. Even if you close the terminal window, forever continues to run in background to ensure that your application restarts every time a crash happens.

How to use forever inside your node application

You can incorporate Forever directly into your node application like below...
var forever = require('forever-monitor');
var childList = new (forever.Monitor)('fileName.js', {
max: 10,
watch: true
child.on('exit', this.callback);

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment