Using forever with Node.js

Problem

I have a few, possibly trivial, questions with using forever with Node.js. From what I have read, forever can be used programatically and it maintains a list with all the scripts that use forever. When that process dies, it automatically spawns a new one until it is stopped.

However, my question is, how does forever do this? Does it add these scripts to be started on boot as well?

Problem courtesy of: cowboybebop

Solution

You can use forever programatically like this:

Using an instance of Forever inside a node.js script:

var forever = require('forever-monitor');

var child = new (forever.Monitor)('your-filename.js', {
max: 3,
silent: true,
options: []
});

child.on('exit', function () {
console.log('your-filename.js has exited after 3 restarts');
});

child.start();

You should take a minute and read over the options available in the excellent documentation for Forever in the README.md

You have a number of events that can be listened for in Forever as well:

  • error [err]: Raised when an error occurs
  • start [process, fvrFile, data]: Raise when the target script is first started.
  • stop [process]: Raised when the target script is stopped by the user
  • save [path, data]: Raised when the target Monitor saves the pid information to disk.
  • restart [forever]: Raised each time the target script is restarted
  • exit [forever]: Raised when the target script actually exits (permenantly).
  • stdout [data]: Raised when data is received from the child process’ stdout
  • stderr [data]: Raised when data is received from the child process’ stderr

It does this by attaching event listeners to the script you’re trying to run and handling them in a graceful manner.

The code is pretty well documented if you want to take a look at exactly how it does it.

You should also read this excellent tutorial on how to keep a process running forever.

As for the second question: No, it does not add it to start at boot. For that, you’d need to add it as an upstart job or use something like Monit to monitor and start it. For that, you should take a look at Deploying Node.js with Upstart and Monit. It’s a great tutorial.

Solution courtesy of: slickplaid

View additional discussion.