DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Keep Node.js Processes Running

How to Keep Node.js Processes Running

Alexander Beletsky user avatar by
Alexander Beletsky
·
Jan. 31, 14 · Interview
Like (0)
Save
Tweet
Share
17.64K Views

Join the DZone community and get the full member experience.

Join For Free

Node.js/Express.js is great for Web API’s and applications. In contrast to known enterprise technologies, Node.js is very special. It’s a single process/threaded environment. If an unhanded exception occurs, the Node.js virtual machine simply stops, leaving the application in an unresponsive state.

Due to the async nature of Node.js, try/catch doesn't always work, even with domains and stuff you have a chance that the application crashes on production while you sleep.

To mitigate the issue, there are few known solutions. The common idea is that there is a watchdog keeping an eye on node processes and if crashed, it restarts the application again.

Recently I’ve used a great library by @mafintosh called respawn. I liked its minimalistic style and decided to try it out.

The bare-bones code is very simple. Without modification of your application, just create file monitor.js with the following code:

var respawn = require('respawn');

var monitor = respawn(['node', 'server.js'], {
    env: {ENV_VAR:'test'}, // set env vars
    cwd: '.',              // set cwd
    maxRestarts:10,        // how many restarts are allowed within 60s
    sleep:1000,            // time to sleep between restarts
});

monitor.start(); // spawn and watch

monitor will spawn new node process and in case of crash it will be restarted. You can also specify maxRestars (I recommend to do that, if something is really bad it won’t be restarted infinitely) and sleep time.

I’ve tried that, by implementing /fail end-point in my app, to see that respawn really works.

app.get('/fail', function (req, res, next) {
  setTimeout(function () {
      var nu = null;
      nu.access();

      res.send('Hello World');
  }, 1000);
});

if I try to hit /fail I’ll see no results in browser, but if I go back to / the application is running in normal state.

But simple respawning of the application is not a complete solution. You need to know what exactly happened to be able to fix issue. Proper logging of your application is essential. I’ll show my small setup around respawn that sends critical message to Logentries, so all crashes are logged.

var respawn = require('respawn');
var util = require('util');
var logger = require('./source/utils/logger');

var proc = respawn(['node', 'app.js'], {
  cwd: '.',
  maxRestarts: 10,
  sleep: 1000,
});

proc.on('spawn', function () {
  util.print('application monitor started...');
});

proc.on('exit', function (code, signal) {
  logger.fatal({msg: 'process exited, code: ' + code + ' signal: ' + signal});
});

proc.on('stdout', function (data) {
  util.print(data.toString());
});

proc.on('stderr', function (data) {
  logger.error({msg: 'process error', data: data.toString()});
});

proc.start();

(Details of logger you can find in this post).

All process output goes to stdout, which is convinient for development, but in case of stderr or exit everything is logged to cloud and notification to dev-team sent.

It worked really nice, now I’m not worried even if something bad happens on production. respawn will make sure that the rest of users are not affected. As a developer, you can much quicker find bugs and push hotfixes.

Node.js application

Published at DZone with permission of Alexander Beletsky, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Cut the Release Inspection Time From 4 Days to 4 Hours
  • Internal Components of Apache ZooKeeper and Their Importance
  • Handling Automatic ID Generation in PostgreSQL With Node.js and Sequelize
  • AIOps Being Powered by Robotic Data Automation

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: