Question

In my application im using uncaughtException to handle the application error.In this how can i restart the server.

Was it helpful?

Solution

Use the forever module.

npm install forever

forever will restart your server any time it quits, for any reason.

This means you can do a process.exit(); in your code any time you want the server to restart.

You'll need a start and stop script to engage forever.

A typical start script would look like this.

#!/bin/sh
./node_modules/forever/bin/forever \
 start \
 -al log.forever \
 -ao log.traffic \
 -ae log.errors \
app.js

A typical stop script would look like this:

#!/bin/sh
./node_modules/forever/bin/forever stop app.js

In your exception handling code would look something like this:

process.on('uncaughtException', function (err) {
    console.log(err.stack);
    process.exit();
});

OTHER TIPS

You could use the built in nodejs cluster feature. With this module, you set up a master and a few workers, and when a worker die, you can spawn a new one. An example from a recent project of mine:

var cluster = require('cluster'),
numCpus = require('os').cpus().length;

if (cluster.isMaster) {

    for (var i = 0; i < numCpus; i++) {
        console.log("Spawning worker...");
        cluster.fork();
    }

    cluster.on('exit', function (worker) {
        console.log("Worker " + worker.pid + " died");
        var newWorker = cluster.fork();
        console.log("Spawning new worker " + newWorker.pid);
    });

}

Forever works well and is simple to setup

You could also try fleet by substack. Fleet makes it really easy to deploy your code to one or many servers. Then you can spawn your server processes using fleet spawn -- node ... and fleet will automatically restart any processes that crash

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top