node.js - How to perform an async operation on exit -


i've been trying perform asynchronous operation before process terminated.

saying 'terminated' mean every possibility of termination:

  • ctrl+c
  • uncaught exception
  • crashes
  • end of code
  • anything..

to knowledge exit event synchronous operations.

reading nodejs docs found beforeexit event async operations :

the 'beforeexit' event not emitted conditions causing explicit termination, such calling process.exit() or uncaught exceptions.

the 'beforeexit' should not used alternative 'exit' event unless intention schedule additional work.

any suggestions?

you can trap signals , perform async task before exiting. call terminator() function before exiting (even javascript error in code):

process.on('exit', function () {     // cleanup such close db     if (db) {         db.close();     } });  // catching signals , before exit ['sighup', 'sigint', 'sigquit', 'sigill', 'sigtrap', 'sigabrt',     'sigbus', 'sigfpe', 'sigusr1', 'sigsegv', 'sigusr2', 'sigterm' ].foreach(function (sig) {     process.on(sig, function () {         terminator(sig);         console.log('signal: ' + sig);     }); });  function terminator(sig) {     if (typeof sig === "string") {         // call async task here , call process.exit() after async task done         myasynctaskbeforeexit(function() {             console.log('received %s - terminating server app ...', sig);             process.exit(1);         });     }     console.log('node server stopped.'); } 

add detail requested in comment:

  • signals explained node's documentation, link refers standard posix signal names
  • the signals should string. however, i've seen others have done check there might other unexpected signals don't know about. want make sure before calling process.exit(). figure doesn't take time check anyway.
  • for db.close(), guess depends on driver using. whether it's sync of async. if it's async, , don't need after db closed, should fine because async db.close() emits close event , event loop continue process whether server exited or not.

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -