A simple way to monitor for any changes in your Node.js application and magically restart the server

computer girl success

In most of my Node.js application servers, I add a simple section of code at the end which watches specific application files, and terminates the server if any are changed.  In tandem with PM2, this allows the code to restart automatically when either pushing a new version, or directly making changes to the code.

There are other applications like nodemon that provide similar functionality, however I feel that PM2 is a better overall process management system.  This capability was not available, so I just added it directly into my applications.

In my application, I perform a simple process.exit(), however you may prefer to raise a signal in your application so you can gracefully shutdown.

console.log('Starting filename watch');

function restartServer(event, filename) {
    console.log('event is: ' + event);
    if (filename) {
        console.log('filename provided: ' + filename);
    } else {
        console.log('filename not provided');
    }
    process.exit(0);
}

fs.watch('jobs_processor.js', restartServer);
fs.watch('lib/hercle_jobs/lib/hercle_jobs.js', restartServer);
fs.watch('lib/hercle_jobs_v2.js', restartServer);
fs.watch('lib/ims_utility.js', restartServer);

Leave a Reply

Your email address will not be published. Required fields are marked *