What is the best practice for gracefully disconnecting Node.js from an external signal?

What is the best practice for gracefully quitting Node.js from an external signal?

I am currently using this in my code:

process.on( 'SIGINT', function() { console.log( "\ngracefully shutting down from SIGINT (Crtl-C)" ) // some other closing procedures go here process.exit( ) }) 
+4
Feb 15 '12 at 18:45
source share
2 answers

It all depends on what your program does, but I would say something like this:

Graceful completion means that all "running" I / O operations (eg, reading files, HTTP request / responses, etc.) must complete, but new functions cannot be started. Thus, your shutdown handler should prevent the possibility of starting any new operations (for example, cancel any port listeners, prevent any new fs calls, etc.), ensure that the currently executing handlers are executed until completion, and then exit the process .

[Edit] Of course, if your application does not care about the above issues, then there really is nothing to do. When the process ends, all open file / socket descriptors will be automatically closed, so there are no problems with resource leaks.

+3
Feb 15 '12 at 18:48
source share

We hope this template helps. I got most of this from Simon Holmes's book β€œGetting MEAN”. The loan goes to him.

 var mongoose = require( 'mongoose' ); var gracefulShutdown; var dbURI = 'mongodb://localhost/xxx'; if (process.env.NODE_ENV === 'production') { dbURI = process.env.MONGOLAB_URI; } mongoose.connect(dbURI); // CONNECTION EVENTS mongoose.connection.on('connected', function () { console.log('Mongoose connected to ' + dbURI); }); mongoose.connection.on('error',function (err) { console.log('Mongoose connection error: ' + err); }); mongoose.connection.on('disconnected', function () { console.log('Mongoose disconnected'); }); // CAPTURE APP TERMINATION / RESTART EVENTS // To be called when process is restarted or terminated gracefulShutdown = function (msg, callback) { mongoose.connection.close(function () { console.log('Mongoose disconnected through ' + msg); callback(); }); }; // For nodemon restarts process.once('SIGUSR2', function () { gracefulShutdown('nodemon restart', function () { process.kill(process.pid, 'SIGUSR2'); }); }); // For app termination process.on('SIGINT', function() { gracefulShutdown('app termination', function () { process.exit(0); }); }); // For Heroku app termination process.on('SIGTERM', function() { gracefulShutdown('Heroku app termination', function () { process.exit(0); }); }); // TODO : For Modulus app termination // BRING IN YOUR SCHEMAS & MODELS. require('./yyy'); 
+1
Dec 16 '14 at 14:21
source share



All Articles