doing a cleanup action just before node.js exits












246














I want to tell node.js to always do something just before it exits, for whatever reason - Ctrl+C, exception, or any other reason.



I tried this:



process.on('exit', function (){
console.log('Goodbye!');
});


Started the process, killed it, and nothing happened; started again, pressed Ctrl+C, and still nothing happened...










share|improve this question






















  • see github.com/nodejs/node/issues/20804
    – pravdomil
    May 18 '18 at 9:55
















246














I want to tell node.js to always do something just before it exits, for whatever reason - Ctrl+C, exception, or any other reason.



I tried this:



process.on('exit', function (){
console.log('Goodbye!');
});


Started the process, killed it, and nothing happened; started again, pressed Ctrl+C, and still nothing happened...










share|improve this question






















  • see github.com/nodejs/node/issues/20804
    – pravdomil
    May 18 '18 at 9:55














246












246








246


104





I want to tell node.js to always do something just before it exits, for whatever reason - Ctrl+C, exception, or any other reason.



I tried this:



process.on('exit', function (){
console.log('Goodbye!');
});


Started the process, killed it, and nothing happened; started again, pressed Ctrl+C, and still nothing happened...










share|improve this question













I want to tell node.js to always do something just before it exits, for whatever reason - Ctrl+C, exception, or any other reason.



I tried this:



process.on('exit', function (){
console.log('Goodbye!');
});


Started the process, killed it, and nothing happened; started again, pressed Ctrl+C, and still nothing happened...







node.js






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 25 '12 at 15:07









Erel Segal-HaleviErel Segal-Halevi

11.3k2368115




11.3k2368115












  • see github.com/nodejs/node/issues/20804
    – pravdomil
    May 18 '18 at 9:55


















  • see github.com/nodejs/node/issues/20804
    – pravdomil
    May 18 '18 at 9:55
















see github.com/nodejs/node/issues/20804
– pravdomil
May 18 '18 at 9:55




see github.com/nodejs/node/issues/20804
– pravdomil
May 18 '18 at 9:55












8 Answers
8






active

oldest

votes


















403














UPDATE:



You can register a handler for process.on('exit') and in any other case(SIGINT or unhandled exception) to call process.exit()



process.stdin.resume();//so the program will not close instantly

function exitHandler(options, exitCode) {
if (options.cleanup) console.log('clean');
if (exitCode || exitCode === 0) console.log(exitCode);
if (options.exit) process.exit();
}

//do something when app is closing
process.on('exit', exitHandler.bind(null,{cleanup:true}));

//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {exit:true}));

// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', exitHandler.bind(null, {exit:true}));
process.on('SIGUSR2', exitHandler.bind(null, {exit:true}));

//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit:true}));





share|improve this answer



















  • 2




    Is there a way to handle both Ctrl+C and a usual exit in the same place, or do I have to write two separate handlers? What about other types of exit, such as unhandled exception - there is a specific handler for that case, but should I handle this with a third copy of the same handler?
    – Erel Segal-Halevi
    Dec 26 '12 at 9:04








  • 7




    Can you explain process.stdin.resume(), how does it work?
    – Rob Fox
    Feb 4 '14 at 19:46






  • 40




    Note that you must only perform synchronous operations in exit handler
    – Lewis
    Feb 10 '15 at 14:23








  • 2




    @KesemDavid I think you should use the beforeExit event instead.
    – Lewis
    Nov 10 '16 at 14:19






  • 14




    This solution has numerous issues. (1) It doesn't report signals to parent processes. (2) It doesn't convey the exit code to the parent process. (3) It doesn't allow for Emacs-like children that ignore Ctrl-C SIGINT. (4) It doesn't allow asynchronous cleanup. (5) It doesn't coordinate a single stderr message across multiple cleanup handlers. I've written a module that does all this, github.com/jtlapp/node-cleanup, originally based on the cleanup.js solution below, but greatly revised based on feedback. I hope it proves helpful.
    – Joe Lapp
    Dec 27 '16 at 5:45



















148














The script below allows having a single handler for all exit conditions. It uses an app specific callback function to perform custom cleanup code.



cleanup.js



// Object to capture process exits and call app specific cleanup function

function noOp() {};

exports.Cleanup = function Cleanup(callback) {

// attach user callback to the process event emitter
// if no callback, it will still exit gracefully on Ctrl-C
callback = callback || noOp;
process.on('cleanup',callback);

// do app specific cleaning before exiting
process.on('exit', function () {
process.emit('cleanup');
});

// catch ctrl+c event and exit normally
process.on('SIGINT', function () {
console.log('Ctrl-C...');
process.exit(2);
});

//catch uncaught exceptions, trace, then exit normally
process.on('uncaughtException', function(e) {
console.log('Uncaught Exception...');
console.log(e.stack);
process.exit(99);
});
};


This code intercepts uncaught exceptions, Ctrl-C and normal exit events. It then calls a single optional user cleanup callback function before exiting, handling all exit conditions with a single object.



The module simply extends the process object instead of defining another event emitter. Without an app specific callback the cleanup defaults to a no op function. This was sufficient for my use where child processes were left running when exiting by Ctrl-C.



You can easily add other exit events such as SIGHUP as desired. Note: per NodeJS manual, SIGKILL cannot have a listener. The test code below demonstrates various ways of using cleanup.js



// test cleanup.js on version 0.10.21

// loads module and registers app specific cleanup callback...
var cleanup = require('./cleanup').Cleanup(myCleanup);
//var cleanup = require('./cleanup').Cleanup(); // will call noOp

// defines app specific callback...
function myCleanup() {
console.log('App specific cleanup code...');
};

// All of the following code is only needed for test demo

// Prevents the program from closing instantly
process.stdin.resume();

// Emits an uncaught exception when called because module does not exist
function error() {
console.log('error');
var x = require('');
};

// Try each of the following one at a time:

// Uncomment the next line to test exiting on an uncaught exception
//setTimeout(error,2000);

// Uncomment the next line to test exiting normally
//setTimeout(function(){process.exit(3)}, 2000);

// Type Ctrl-C to test forced exit





share|improve this answer



















  • 21




    This answer deserves more credit than it gets.
    – Pier-Luc Gendreau
    Nov 18 '14 at 23:33






  • 6




    I've found this code indispensable and created a node package for it, with modifications, crediting you and this SO answer. Hope that's okay, @CanyonCasa. Thank you! npmjs.com/package/node-cleanup
    – Joe Lapp
    Sep 13 '16 at 16:07






  • 3




    I love the cleanup. But I don't like the process.exit(0); cons.org/cracauer/sigint.html My feeling is you should let the kernel handle the destruction. You are not exiting the same way that a SIGINT. SIGINT doesn't exit with 2. You are mistaking the SIGINT with error code. They aren't the same. Actually Ctrl+C exist with 130. Not 2. tldp.org/LDP/abs/html/exitcodes.html
    – Banjocat
    Nov 18 '16 at 2:44






  • 4




    I have rewritten npmjs.com/package/node-cleanup so that SIGINT handling works well with other processes, per @Banjocat's link. It also now correctly relays signals to the parent process instead of calling process.exit(). Cleanup handlers now have the flexibility to behave as a function of exit code or signal, and cleanup handlers can be uninstalled, as necessary to support asynchronous cleanup or prevent cyclic cleanup. It now has little resemblance to the above code.
    – Joe Lapp
    Dec 27 '16 at 5:28








  • 3




    Forgot to mention that I also made a (hopefully) comprehensive test suite.
    – Joe Lapp
    Dec 27 '16 at 5:36



















15














"exit" is an event that gets triggered when node finish it's event loop internally, it's not triggered when you terminate the process externally.



What you're looking for is executing something on a SIGINT.



The docs at http://nodejs.org/api/process.html#process_signal_events give an example:



Example of listening for SIGINT:



// Start reading from stdin so we don't exit.
process.stdin.resume();

process.on('SIGINT', function () {
console.log('Got SIGINT. Press Control-D to exit.');
});


Note: this seems to interrupt the sigint and you would need to call process.exit() when you finish with your code.






share|improve this answer























  • Is there a way to handle both Ctrl+C and a usual exit in the same place? Or do I have to write two identical handlers?
    – Erel Segal-Halevi
    Dec 25 '12 at 20:49










  • Just as a note, if you have to end node by a kill command doing kill -2 will pass the SIGINT code. We have to do it this way because we have node logging to a txt file so Ctrl + C is not possible.
    – Aust
    Feb 14 '13 at 23:22



















8














This catches every exit event I can find that can be handled. Seems quite reliable and clean so far.



[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((eventType) => {
process.on(eventType, cleanUpServer.bind(null, eventType));
})





share|improve this answer





























    5














    Just wanted to mention death package here: https://github.com/jprichardson/node-death



    Example:



    var ON_DEATH = require('death')({uncaughtException: true}); //this is intentionally ugly

    ON_DEATH(function(signal, err) {
    //clean up code here
    })





    share|improve this answer





























      5














      function fnAsyncTest(callback) {
      require('fs').writeFile('async.txt', 'bye!', callback);
      }

      function fnSyncTest() {
      for (var i = 0; i < 10; i++) {}
      }

      function killProcess() {

      if (process.exitTimeoutId) {
      return;
      }

      process.exitTimeoutId = setTimeout(process.exit, 5000);
      console.log('process will exit in 5 seconds');

      fnAsyncTest(function() {
      console.log('async op. done', arguments);
      });

      if (!fnSyncTest()) {
      console.log('sync op. done');
      }
      }

      // https://nodejs.org/api/process.html#process_signal_events
      process.on('SIGTERM', killProcess);
      process.on('SIGINT', killProcess);

      process.on('uncaughtException', function(e) {

      console.log('[uncaughtException] app will be terminated: ', e.stack);

      killProcess();
      /**
      * @https://nodejs.org/api/process.html#process_event_uncaughtexception
      *
      * 'uncaughtException' should be used to perform synchronous cleanup before shutting down the process.
      * It is not safe to resume normal operation after 'uncaughtException'.
      * If you do use it, restart your application after every unhandled exception!
      *
      * You have been warned.
      */
      });

      console.log('App is running...');
      console.log('Try to press CTRL+C or SIGNAL the process with PID: ', process.pid);

      process.stdin.resume();
      // just for testing





      share|improve this answer



















      • 1




        This answer deserves all the glory, but because there is no explanation, there is no up-vote either unfortunately. What significant about this answer is, the doc says, "Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. ", and this answer overcomes that limitation!
        – xpt
        Feb 25 '18 at 14:36



















      0














      io.js has an exit and a beforeExit event, which do what you want.






      share|improve this answer





























        -1














        In the case where the process was spawned by another node process, like:



        var child = spawn('gulp', ['watch'], {
        stdio: 'inherit',
        });


        And you try to kill it later, via:



        child.kill();


        This is how you handle the event [on the child]:



        process.on('SIGTERM', function() {
        console.log('Goodbye!');
        });





        share|improve this answer





















          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14031763%2fdoing-a-cleanup-action-just-before-node-js-exits%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          8 Answers
          8






          active

          oldest

          votes








          8 Answers
          8






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          403














          UPDATE:



          You can register a handler for process.on('exit') and in any other case(SIGINT or unhandled exception) to call process.exit()



          process.stdin.resume();//so the program will not close instantly

          function exitHandler(options, exitCode) {
          if (options.cleanup) console.log('clean');
          if (exitCode || exitCode === 0) console.log(exitCode);
          if (options.exit) process.exit();
          }

          //do something when app is closing
          process.on('exit', exitHandler.bind(null,{cleanup:true}));

          //catches ctrl+c event
          process.on('SIGINT', exitHandler.bind(null, {exit:true}));

          // catches "kill pid" (for example: nodemon restart)
          process.on('SIGUSR1', exitHandler.bind(null, {exit:true}));
          process.on('SIGUSR2', exitHandler.bind(null, {exit:true}));

          //catches uncaught exceptions
          process.on('uncaughtException', exitHandler.bind(null, {exit:true}));





          share|improve this answer



















          • 2




            Is there a way to handle both Ctrl+C and a usual exit in the same place, or do I have to write two separate handlers? What about other types of exit, such as unhandled exception - there is a specific handler for that case, but should I handle this with a third copy of the same handler?
            – Erel Segal-Halevi
            Dec 26 '12 at 9:04








          • 7




            Can you explain process.stdin.resume(), how does it work?
            – Rob Fox
            Feb 4 '14 at 19:46






          • 40




            Note that you must only perform synchronous operations in exit handler
            – Lewis
            Feb 10 '15 at 14:23








          • 2




            @KesemDavid I think you should use the beforeExit event instead.
            – Lewis
            Nov 10 '16 at 14:19






          • 14




            This solution has numerous issues. (1) It doesn't report signals to parent processes. (2) It doesn't convey the exit code to the parent process. (3) It doesn't allow for Emacs-like children that ignore Ctrl-C SIGINT. (4) It doesn't allow asynchronous cleanup. (5) It doesn't coordinate a single stderr message across multiple cleanup handlers. I've written a module that does all this, github.com/jtlapp/node-cleanup, originally based on the cleanup.js solution below, but greatly revised based on feedback. I hope it proves helpful.
            – Joe Lapp
            Dec 27 '16 at 5:45
















          403














          UPDATE:



          You can register a handler for process.on('exit') and in any other case(SIGINT or unhandled exception) to call process.exit()



          process.stdin.resume();//so the program will not close instantly

          function exitHandler(options, exitCode) {
          if (options.cleanup) console.log('clean');
          if (exitCode || exitCode === 0) console.log(exitCode);
          if (options.exit) process.exit();
          }

          //do something when app is closing
          process.on('exit', exitHandler.bind(null,{cleanup:true}));

          //catches ctrl+c event
          process.on('SIGINT', exitHandler.bind(null, {exit:true}));

          // catches "kill pid" (for example: nodemon restart)
          process.on('SIGUSR1', exitHandler.bind(null, {exit:true}));
          process.on('SIGUSR2', exitHandler.bind(null, {exit:true}));

          //catches uncaught exceptions
          process.on('uncaughtException', exitHandler.bind(null, {exit:true}));





          share|improve this answer



















          • 2




            Is there a way to handle both Ctrl+C and a usual exit in the same place, or do I have to write two separate handlers? What about other types of exit, such as unhandled exception - there is a specific handler for that case, but should I handle this with a third copy of the same handler?
            – Erel Segal-Halevi
            Dec 26 '12 at 9:04








          • 7




            Can you explain process.stdin.resume(), how does it work?
            – Rob Fox
            Feb 4 '14 at 19:46






          • 40




            Note that you must only perform synchronous operations in exit handler
            – Lewis
            Feb 10 '15 at 14:23








          • 2




            @KesemDavid I think you should use the beforeExit event instead.
            – Lewis
            Nov 10 '16 at 14:19






          • 14




            This solution has numerous issues. (1) It doesn't report signals to parent processes. (2) It doesn't convey the exit code to the parent process. (3) It doesn't allow for Emacs-like children that ignore Ctrl-C SIGINT. (4) It doesn't allow asynchronous cleanup. (5) It doesn't coordinate a single stderr message across multiple cleanup handlers. I've written a module that does all this, github.com/jtlapp/node-cleanup, originally based on the cleanup.js solution below, but greatly revised based on feedback. I hope it proves helpful.
            – Joe Lapp
            Dec 27 '16 at 5:45














          403












          403








          403






          UPDATE:



          You can register a handler for process.on('exit') and in any other case(SIGINT or unhandled exception) to call process.exit()



          process.stdin.resume();//so the program will not close instantly

          function exitHandler(options, exitCode) {
          if (options.cleanup) console.log('clean');
          if (exitCode || exitCode === 0) console.log(exitCode);
          if (options.exit) process.exit();
          }

          //do something when app is closing
          process.on('exit', exitHandler.bind(null,{cleanup:true}));

          //catches ctrl+c event
          process.on('SIGINT', exitHandler.bind(null, {exit:true}));

          // catches "kill pid" (for example: nodemon restart)
          process.on('SIGUSR1', exitHandler.bind(null, {exit:true}));
          process.on('SIGUSR2', exitHandler.bind(null, {exit:true}));

          //catches uncaught exceptions
          process.on('uncaughtException', exitHandler.bind(null, {exit:true}));





          share|improve this answer














          UPDATE:



          You can register a handler for process.on('exit') and in any other case(SIGINT or unhandled exception) to call process.exit()



          process.stdin.resume();//so the program will not close instantly

          function exitHandler(options, exitCode) {
          if (options.cleanup) console.log('clean');
          if (exitCode || exitCode === 0) console.log(exitCode);
          if (options.exit) process.exit();
          }

          //do something when app is closing
          process.on('exit', exitHandler.bind(null,{cleanup:true}));

          //catches ctrl+c event
          process.on('SIGINT', exitHandler.bind(null, {exit:true}));

          // catches "kill pid" (for example: nodemon restart)
          process.on('SIGUSR1', exitHandler.bind(null, {exit:true}));
          process.on('SIGUSR2', exitHandler.bind(null, {exit:true}));

          //catches uncaught exceptions
          process.on('uncaughtException', exitHandler.bind(null, {exit:true}));






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Aug 11 '18 at 13:32









          dopeddude

          2,6022334




          2,6022334










          answered Dec 25 '12 at 18:17









          Emil CondreaEmil Condrea

          6,49772650




          6,49772650








          • 2




            Is there a way to handle both Ctrl+C and a usual exit in the same place, or do I have to write two separate handlers? What about other types of exit, such as unhandled exception - there is a specific handler for that case, but should I handle this with a third copy of the same handler?
            – Erel Segal-Halevi
            Dec 26 '12 at 9:04








          • 7




            Can you explain process.stdin.resume(), how does it work?
            – Rob Fox
            Feb 4 '14 at 19:46






          • 40




            Note that you must only perform synchronous operations in exit handler
            – Lewis
            Feb 10 '15 at 14:23








          • 2




            @KesemDavid I think you should use the beforeExit event instead.
            – Lewis
            Nov 10 '16 at 14:19






          • 14




            This solution has numerous issues. (1) It doesn't report signals to parent processes. (2) It doesn't convey the exit code to the parent process. (3) It doesn't allow for Emacs-like children that ignore Ctrl-C SIGINT. (4) It doesn't allow asynchronous cleanup. (5) It doesn't coordinate a single stderr message across multiple cleanup handlers. I've written a module that does all this, github.com/jtlapp/node-cleanup, originally based on the cleanup.js solution below, but greatly revised based on feedback. I hope it proves helpful.
            – Joe Lapp
            Dec 27 '16 at 5:45














          • 2




            Is there a way to handle both Ctrl+C and a usual exit in the same place, or do I have to write two separate handlers? What about other types of exit, such as unhandled exception - there is a specific handler for that case, but should I handle this with a third copy of the same handler?
            – Erel Segal-Halevi
            Dec 26 '12 at 9:04








          • 7




            Can you explain process.stdin.resume(), how does it work?
            – Rob Fox
            Feb 4 '14 at 19:46






          • 40




            Note that you must only perform synchronous operations in exit handler
            – Lewis
            Feb 10 '15 at 14:23








          • 2




            @KesemDavid I think you should use the beforeExit event instead.
            – Lewis
            Nov 10 '16 at 14:19






          • 14




            This solution has numerous issues. (1) It doesn't report signals to parent processes. (2) It doesn't convey the exit code to the parent process. (3) It doesn't allow for Emacs-like children that ignore Ctrl-C SIGINT. (4) It doesn't allow asynchronous cleanup. (5) It doesn't coordinate a single stderr message across multiple cleanup handlers. I've written a module that does all this, github.com/jtlapp/node-cleanup, originally based on the cleanup.js solution below, but greatly revised based on feedback. I hope it proves helpful.
            – Joe Lapp
            Dec 27 '16 at 5:45








          2




          2




          Is there a way to handle both Ctrl+C and a usual exit in the same place, or do I have to write two separate handlers? What about other types of exit, such as unhandled exception - there is a specific handler for that case, but should I handle this with a third copy of the same handler?
          – Erel Segal-Halevi
          Dec 26 '12 at 9:04






          Is there a way to handle both Ctrl+C and a usual exit in the same place, or do I have to write two separate handlers? What about other types of exit, such as unhandled exception - there is a specific handler for that case, but should I handle this with a third copy of the same handler?
          – Erel Segal-Halevi
          Dec 26 '12 at 9:04






          7




          7




          Can you explain process.stdin.resume(), how does it work?
          – Rob Fox
          Feb 4 '14 at 19:46




          Can you explain process.stdin.resume(), how does it work?
          – Rob Fox
          Feb 4 '14 at 19:46




          40




          40




          Note that you must only perform synchronous operations in exit handler
          – Lewis
          Feb 10 '15 at 14:23






          Note that you must only perform synchronous operations in exit handler
          – Lewis
          Feb 10 '15 at 14:23






          2




          2




          @KesemDavid I think you should use the beforeExit event instead.
          – Lewis
          Nov 10 '16 at 14:19




          @KesemDavid I think you should use the beforeExit event instead.
          – Lewis
          Nov 10 '16 at 14:19




          14




          14




          This solution has numerous issues. (1) It doesn't report signals to parent processes. (2) It doesn't convey the exit code to the parent process. (3) It doesn't allow for Emacs-like children that ignore Ctrl-C SIGINT. (4) It doesn't allow asynchronous cleanup. (5) It doesn't coordinate a single stderr message across multiple cleanup handlers. I've written a module that does all this, github.com/jtlapp/node-cleanup, originally based on the cleanup.js solution below, but greatly revised based on feedback. I hope it proves helpful.
          – Joe Lapp
          Dec 27 '16 at 5:45




          This solution has numerous issues. (1) It doesn't report signals to parent processes. (2) It doesn't convey the exit code to the parent process. (3) It doesn't allow for Emacs-like children that ignore Ctrl-C SIGINT. (4) It doesn't allow asynchronous cleanup. (5) It doesn't coordinate a single stderr message across multiple cleanup handlers. I've written a module that does all this, github.com/jtlapp/node-cleanup, originally based on the cleanup.js solution below, but greatly revised based on feedback. I hope it proves helpful.
          – Joe Lapp
          Dec 27 '16 at 5:45













          148














          The script below allows having a single handler for all exit conditions. It uses an app specific callback function to perform custom cleanup code.



          cleanup.js



          // Object to capture process exits and call app specific cleanup function

          function noOp() {};

          exports.Cleanup = function Cleanup(callback) {

          // attach user callback to the process event emitter
          // if no callback, it will still exit gracefully on Ctrl-C
          callback = callback || noOp;
          process.on('cleanup',callback);

          // do app specific cleaning before exiting
          process.on('exit', function () {
          process.emit('cleanup');
          });

          // catch ctrl+c event and exit normally
          process.on('SIGINT', function () {
          console.log('Ctrl-C...');
          process.exit(2);
          });

          //catch uncaught exceptions, trace, then exit normally
          process.on('uncaughtException', function(e) {
          console.log('Uncaught Exception...');
          console.log(e.stack);
          process.exit(99);
          });
          };


          This code intercepts uncaught exceptions, Ctrl-C and normal exit events. It then calls a single optional user cleanup callback function before exiting, handling all exit conditions with a single object.



          The module simply extends the process object instead of defining another event emitter. Without an app specific callback the cleanup defaults to a no op function. This was sufficient for my use where child processes were left running when exiting by Ctrl-C.



          You can easily add other exit events such as SIGHUP as desired. Note: per NodeJS manual, SIGKILL cannot have a listener. The test code below demonstrates various ways of using cleanup.js



          // test cleanup.js on version 0.10.21

          // loads module and registers app specific cleanup callback...
          var cleanup = require('./cleanup').Cleanup(myCleanup);
          //var cleanup = require('./cleanup').Cleanup(); // will call noOp

          // defines app specific callback...
          function myCleanup() {
          console.log('App specific cleanup code...');
          };

          // All of the following code is only needed for test demo

          // Prevents the program from closing instantly
          process.stdin.resume();

          // Emits an uncaught exception when called because module does not exist
          function error() {
          console.log('error');
          var x = require('');
          };

          // Try each of the following one at a time:

          // Uncomment the next line to test exiting on an uncaught exception
          //setTimeout(error,2000);

          // Uncomment the next line to test exiting normally
          //setTimeout(function(){process.exit(3)}, 2000);

          // Type Ctrl-C to test forced exit





          share|improve this answer



















          • 21




            This answer deserves more credit than it gets.
            – Pier-Luc Gendreau
            Nov 18 '14 at 23:33






          • 6




            I've found this code indispensable and created a node package for it, with modifications, crediting you and this SO answer. Hope that's okay, @CanyonCasa. Thank you! npmjs.com/package/node-cleanup
            – Joe Lapp
            Sep 13 '16 at 16:07






          • 3




            I love the cleanup. But I don't like the process.exit(0); cons.org/cracauer/sigint.html My feeling is you should let the kernel handle the destruction. You are not exiting the same way that a SIGINT. SIGINT doesn't exit with 2. You are mistaking the SIGINT with error code. They aren't the same. Actually Ctrl+C exist with 130. Not 2. tldp.org/LDP/abs/html/exitcodes.html
            – Banjocat
            Nov 18 '16 at 2:44






          • 4




            I have rewritten npmjs.com/package/node-cleanup so that SIGINT handling works well with other processes, per @Banjocat's link. It also now correctly relays signals to the parent process instead of calling process.exit(). Cleanup handlers now have the flexibility to behave as a function of exit code or signal, and cleanup handlers can be uninstalled, as necessary to support asynchronous cleanup or prevent cyclic cleanup. It now has little resemblance to the above code.
            – Joe Lapp
            Dec 27 '16 at 5:28








          • 3




            Forgot to mention that I also made a (hopefully) comprehensive test suite.
            – Joe Lapp
            Dec 27 '16 at 5:36
















          148














          The script below allows having a single handler for all exit conditions. It uses an app specific callback function to perform custom cleanup code.



          cleanup.js



          // Object to capture process exits and call app specific cleanup function

          function noOp() {};

          exports.Cleanup = function Cleanup(callback) {

          // attach user callback to the process event emitter
          // if no callback, it will still exit gracefully on Ctrl-C
          callback = callback || noOp;
          process.on('cleanup',callback);

          // do app specific cleaning before exiting
          process.on('exit', function () {
          process.emit('cleanup');
          });

          // catch ctrl+c event and exit normally
          process.on('SIGINT', function () {
          console.log('Ctrl-C...');
          process.exit(2);
          });

          //catch uncaught exceptions, trace, then exit normally
          process.on('uncaughtException', function(e) {
          console.log('Uncaught Exception...');
          console.log(e.stack);
          process.exit(99);
          });
          };


          This code intercepts uncaught exceptions, Ctrl-C and normal exit events. It then calls a single optional user cleanup callback function before exiting, handling all exit conditions with a single object.



          The module simply extends the process object instead of defining another event emitter. Without an app specific callback the cleanup defaults to a no op function. This was sufficient for my use where child processes were left running when exiting by Ctrl-C.



          You can easily add other exit events such as SIGHUP as desired. Note: per NodeJS manual, SIGKILL cannot have a listener. The test code below demonstrates various ways of using cleanup.js



          // test cleanup.js on version 0.10.21

          // loads module and registers app specific cleanup callback...
          var cleanup = require('./cleanup').Cleanup(myCleanup);
          //var cleanup = require('./cleanup').Cleanup(); // will call noOp

          // defines app specific callback...
          function myCleanup() {
          console.log('App specific cleanup code...');
          };

          // All of the following code is only needed for test demo

          // Prevents the program from closing instantly
          process.stdin.resume();

          // Emits an uncaught exception when called because module does not exist
          function error() {
          console.log('error');
          var x = require('');
          };

          // Try each of the following one at a time:

          // Uncomment the next line to test exiting on an uncaught exception
          //setTimeout(error,2000);

          // Uncomment the next line to test exiting normally
          //setTimeout(function(){process.exit(3)}, 2000);

          // Type Ctrl-C to test forced exit





          share|improve this answer



















          • 21




            This answer deserves more credit than it gets.
            – Pier-Luc Gendreau
            Nov 18 '14 at 23:33






          • 6




            I've found this code indispensable and created a node package for it, with modifications, crediting you and this SO answer. Hope that's okay, @CanyonCasa. Thank you! npmjs.com/package/node-cleanup
            – Joe Lapp
            Sep 13 '16 at 16:07






          • 3




            I love the cleanup. But I don't like the process.exit(0); cons.org/cracauer/sigint.html My feeling is you should let the kernel handle the destruction. You are not exiting the same way that a SIGINT. SIGINT doesn't exit with 2. You are mistaking the SIGINT with error code. They aren't the same. Actually Ctrl+C exist with 130. Not 2. tldp.org/LDP/abs/html/exitcodes.html
            – Banjocat
            Nov 18 '16 at 2:44






          • 4




            I have rewritten npmjs.com/package/node-cleanup so that SIGINT handling works well with other processes, per @Banjocat's link. It also now correctly relays signals to the parent process instead of calling process.exit(). Cleanup handlers now have the flexibility to behave as a function of exit code or signal, and cleanup handlers can be uninstalled, as necessary to support asynchronous cleanup or prevent cyclic cleanup. It now has little resemblance to the above code.
            – Joe Lapp
            Dec 27 '16 at 5:28








          • 3




            Forgot to mention that I also made a (hopefully) comprehensive test suite.
            – Joe Lapp
            Dec 27 '16 at 5:36














          148












          148








          148






          The script below allows having a single handler for all exit conditions. It uses an app specific callback function to perform custom cleanup code.



          cleanup.js



          // Object to capture process exits and call app specific cleanup function

          function noOp() {};

          exports.Cleanup = function Cleanup(callback) {

          // attach user callback to the process event emitter
          // if no callback, it will still exit gracefully on Ctrl-C
          callback = callback || noOp;
          process.on('cleanup',callback);

          // do app specific cleaning before exiting
          process.on('exit', function () {
          process.emit('cleanup');
          });

          // catch ctrl+c event and exit normally
          process.on('SIGINT', function () {
          console.log('Ctrl-C...');
          process.exit(2);
          });

          //catch uncaught exceptions, trace, then exit normally
          process.on('uncaughtException', function(e) {
          console.log('Uncaught Exception...');
          console.log(e.stack);
          process.exit(99);
          });
          };


          This code intercepts uncaught exceptions, Ctrl-C and normal exit events. It then calls a single optional user cleanup callback function before exiting, handling all exit conditions with a single object.



          The module simply extends the process object instead of defining another event emitter. Without an app specific callback the cleanup defaults to a no op function. This was sufficient for my use where child processes were left running when exiting by Ctrl-C.



          You can easily add other exit events such as SIGHUP as desired. Note: per NodeJS manual, SIGKILL cannot have a listener. The test code below demonstrates various ways of using cleanup.js



          // test cleanup.js on version 0.10.21

          // loads module and registers app specific cleanup callback...
          var cleanup = require('./cleanup').Cleanup(myCleanup);
          //var cleanup = require('./cleanup').Cleanup(); // will call noOp

          // defines app specific callback...
          function myCleanup() {
          console.log('App specific cleanup code...');
          };

          // All of the following code is only needed for test demo

          // Prevents the program from closing instantly
          process.stdin.resume();

          // Emits an uncaught exception when called because module does not exist
          function error() {
          console.log('error');
          var x = require('');
          };

          // Try each of the following one at a time:

          // Uncomment the next line to test exiting on an uncaught exception
          //setTimeout(error,2000);

          // Uncomment the next line to test exiting normally
          //setTimeout(function(){process.exit(3)}, 2000);

          // Type Ctrl-C to test forced exit





          share|improve this answer














          The script below allows having a single handler for all exit conditions. It uses an app specific callback function to perform custom cleanup code.



          cleanup.js



          // Object to capture process exits and call app specific cleanup function

          function noOp() {};

          exports.Cleanup = function Cleanup(callback) {

          // attach user callback to the process event emitter
          // if no callback, it will still exit gracefully on Ctrl-C
          callback = callback || noOp;
          process.on('cleanup',callback);

          // do app specific cleaning before exiting
          process.on('exit', function () {
          process.emit('cleanup');
          });

          // catch ctrl+c event and exit normally
          process.on('SIGINT', function () {
          console.log('Ctrl-C...');
          process.exit(2);
          });

          //catch uncaught exceptions, trace, then exit normally
          process.on('uncaughtException', function(e) {
          console.log('Uncaught Exception...');
          console.log(e.stack);
          process.exit(99);
          });
          };


          This code intercepts uncaught exceptions, Ctrl-C and normal exit events. It then calls a single optional user cleanup callback function before exiting, handling all exit conditions with a single object.



          The module simply extends the process object instead of defining another event emitter. Without an app specific callback the cleanup defaults to a no op function. This was sufficient for my use where child processes were left running when exiting by Ctrl-C.



          You can easily add other exit events such as SIGHUP as desired. Note: per NodeJS manual, SIGKILL cannot have a listener. The test code below demonstrates various ways of using cleanup.js



          // test cleanup.js on version 0.10.21

          // loads module and registers app specific cleanup callback...
          var cleanup = require('./cleanup').Cleanup(myCleanup);
          //var cleanup = require('./cleanup').Cleanup(); // will call noOp

          // defines app specific callback...
          function myCleanup() {
          console.log('App specific cleanup code...');
          };

          // All of the following code is only needed for test demo

          // Prevents the program from closing instantly
          process.stdin.resume();

          // Emits an uncaught exception when called because module does not exist
          function error() {
          console.log('error');
          var x = require('');
          };

          // Try each of the following one at a time:

          // Uncomment the next line to test exiting on an uncaught exception
          //setTimeout(error,2000);

          // Uncomment the next line to test exiting normally
          //setTimeout(function(){process.exit(3)}, 2000);

          // Type Ctrl-C to test forced exit






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 18 '14 at 23:32









          Pier-Luc Gendreau

          9,91434354




          9,91434354










          answered Feb 22 '14 at 0:25









          CanyonCasaCanyonCasa

          1,481162




          1,481162








          • 21




            This answer deserves more credit than it gets.
            – Pier-Luc Gendreau
            Nov 18 '14 at 23:33






          • 6




            I've found this code indispensable and created a node package for it, with modifications, crediting you and this SO answer. Hope that's okay, @CanyonCasa. Thank you! npmjs.com/package/node-cleanup
            – Joe Lapp
            Sep 13 '16 at 16:07






          • 3




            I love the cleanup. But I don't like the process.exit(0); cons.org/cracauer/sigint.html My feeling is you should let the kernel handle the destruction. You are not exiting the same way that a SIGINT. SIGINT doesn't exit with 2. You are mistaking the SIGINT with error code. They aren't the same. Actually Ctrl+C exist with 130. Not 2. tldp.org/LDP/abs/html/exitcodes.html
            – Banjocat
            Nov 18 '16 at 2:44






          • 4




            I have rewritten npmjs.com/package/node-cleanup so that SIGINT handling works well with other processes, per @Banjocat's link. It also now correctly relays signals to the parent process instead of calling process.exit(). Cleanup handlers now have the flexibility to behave as a function of exit code or signal, and cleanup handlers can be uninstalled, as necessary to support asynchronous cleanup or prevent cyclic cleanup. It now has little resemblance to the above code.
            – Joe Lapp
            Dec 27 '16 at 5:28








          • 3




            Forgot to mention that I also made a (hopefully) comprehensive test suite.
            – Joe Lapp
            Dec 27 '16 at 5:36














          • 21




            This answer deserves more credit than it gets.
            – Pier-Luc Gendreau
            Nov 18 '14 at 23:33






          • 6




            I've found this code indispensable and created a node package for it, with modifications, crediting you and this SO answer. Hope that's okay, @CanyonCasa. Thank you! npmjs.com/package/node-cleanup
            – Joe Lapp
            Sep 13 '16 at 16:07






          • 3




            I love the cleanup. But I don't like the process.exit(0); cons.org/cracauer/sigint.html My feeling is you should let the kernel handle the destruction. You are not exiting the same way that a SIGINT. SIGINT doesn't exit with 2. You are mistaking the SIGINT with error code. They aren't the same. Actually Ctrl+C exist with 130. Not 2. tldp.org/LDP/abs/html/exitcodes.html
            – Banjocat
            Nov 18 '16 at 2:44






          • 4




            I have rewritten npmjs.com/package/node-cleanup so that SIGINT handling works well with other processes, per @Banjocat's link. It also now correctly relays signals to the parent process instead of calling process.exit(). Cleanup handlers now have the flexibility to behave as a function of exit code or signal, and cleanup handlers can be uninstalled, as necessary to support asynchronous cleanup or prevent cyclic cleanup. It now has little resemblance to the above code.
            – Joe Lapp
            Dec 27 '16 at 5:28








          • 3




            Forgot to mention that I also made a (hopefully) comprehensive test suite.
            – Joe Lapp
            Dec 27 '16 at 5:36








          21




          21




          This answer deserves more credit than it gets.
          – Pier-Luc Gendreau
          Nov 18 '14 at 23:33




          This answer deserves more credit than it gets.
          – Pier-Luc Gendreau
          Nov 18 '14 at 23:33




          6




          6




          I've found this code indispensable and created a node package for it, with modifications, crediting you and this SO answer. Hope that's okay, @CanyonCasa. Thank you! npmjs.com/package/node-cleanup
          – Joe Lapp
          Sep 13 '16 at 16:07




          I've found this code indispensable and created a node package for it, with modifications, crediting you and this SO answer. Hope that's okay, @CanyonCasa. Thank you! npmjs.com/package/node-cleanup
          – Joe Lapp
          Sep 13 '16 at 16:07




          3




          3




          I love the cleanup. But I don't like the process.exit(0); cons.org/cracauer/sigint.html My feeling is you should let the kernel handle the destruction. You are not exiting the same way that a SIGINT. SIGINT doesn't exit with 2. You are mistaking the SIGINT with error code. They aren't the same. Actually Ctrl+C exist with 130. Not 2. tldp.org/LDP/abs/html/exitcodes.html
          – Banjocat
          Nov 18 '16 at 2:44




          I love the cleanup. But I don't like the process.exit(0); cons.org/cracauer/sigint.html My feeling is you should let the kernel handle the destruction. You are not exiting the same way that a SIGINT. SIGINT doesn't exit with 2. You are mistaking the SIGINT with error code. They aren't the same. Actually Ctrl+C exist with 130. Not 2. tldp.org/LDP/abs/html/exitcodes.html
          – Banjocat
          Nov 18 '16 at 2:44




          4




          4




          I have rewritten npmjs.com/package/node-cleanup so that SIGINT handling works well with other processes, per @Banjocat's link. It also now correctly relays signals to the parent process instead of calling process.exit(). Cleanup handlers now have the flexibility to behave as a function of exit code or signal, and cleanup handlers can be uninstalled, as necessary to support asynchronous cleanup or prevent cyclic cleanup. It now has little resemblance to the above code.
          – Joe Lapp
          Dec 27 '16 at 5:28






          I have rewritten npmjs.com/package/node-cleanup so that SIGINT handling works well with other processes, per @Banjocat's link. It also now correctly relays signals to the parent process instead of calling process.exit(). Cleanup handlers now have the flexibility to behave as a function of exit code or signal, and cleanup handlers can be uninstalled, as necessary to support asynchronous cleanup or prevent cyclic cleanup. It now has little resemblance to the above code.
          – Joe Lapp
          Dec 27 '16 at 5:28






          3




          3




          Forgot to mention that I also made a (hopefully) comprehensive test suite.
          – Joe Lapp
          Dec 27 '16 at 5:36




          Forgot to mention that I also made a (hopefully) comprehensive test suite.
          – Joe Lapp
          Dec 27 '16 at 5:36











          15














          "exit" is an event that gets triggered when node finish it's event loop internally, it's not triggered when you terminate the process externally.



          What you're looking for is executing something on a SIGINT.



          The docs at http://nodejs.org/api/process.html#process_signal_events give an example:



          Example of listening for SIGINT:



          // Start reading from stdin so we don't exit.
          process.stdin.resume();

          process.on('SIGINT', function () {
          console.log('Got SIGINT. Press Control-D to exit.');
          });


          Note: this seems to interrupt the sigint and you would need to call process.exit() when you finish with your code.






          share|improve this answer























          • Is there a way to handle both Ctrl+C and a usual exit in the same place? Or do I have to write two identical handlers?
            – Erel Segal-Halevi
            Dec 25 '12 at 20:49










          • Just as a note, if you have to end node by a kill command doing kill -2 will pass the SIGINT code. We have to do it this way because we have node logging to a txt file so Ctrl + C is not possible.
            – Aust
            Feb 14 '13 at 23:22
















          15














          "exit" is an event that gets triggered when node finish it's event loop internally, it's not triggered when you terminate the process externally.



          What you're looking for is executing something on a SIGINT.



          The docs at http://nodejs.org/api/process.html#process_signal_events give an example:



          Example of listening for SIGINT:



          // Start reading from stdin so we don't exit.
          process.stdin.resume();

          process.on('SIGINT', function () {
          console.log('Got SIGINT. Press Control-D to exit.');
          });


          Note: this seems to interrupt the sigint and you would need to call process.exit() when you finish with your code.






          share|improve this answer























          • Is there a way to handle both Ctrl+C and a usual exit in the same place? Or do I have to write two identical handlers?
            – Erel Segal-Halevi
            Dec 25 '12 at 20:49










          • Just as a note, if you have to end node by a kill command doing kill -2 will pass the SIGINT code. We have to do it this way because we have node logging to a txt file so Ctrl + C is not possible.
            – Aust
            Feb 14 '13 at 23:22














          15












          15








          15






          "exit" is an event that gets triggered when node finish it's event loop internally, it's not triggered when you terminate the process externally.



          What you're looking for is executing something on a SIGINT.



          The docs at http://nodejs.org/api/process.html#process_signal_events give an example:



          Example of listening for SIGINT:



          // Start reading from stdin so we don't exit.
          process.stdin.resume();

          process.on('SIGINT', function () {
          console.log('Got SIGINT. Press Control-D to exit.');
          });


          Note: this seems to interrupt the sigint and you would need to call process.exit() when you finish with your code.






          share|improve this answer














          "exit" is an event that gets triggered when node finish it's event loop internally, it's not triggered when you terminate the process externally.



          What you're looking for is executing something on a SIGINT.



          The docs at http://nodejs.org/api/process.html#process_signal_events give an example:



          Example of listening for SIGINT:



          // Start reading from stdin so we don't exit.
          process.stdin.resume();

          process.on('SIGINT', function () {
          console.log('Got SIGINT. Press Control-D to exit.');
          });


          Note: this seems to interrupt the sigint and you would need to call process.exit() when you finish with your code.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 25 '12 at 20:26

























          answered Dec 25 '12 at 20:11









          user1278519user1278519

          66258




          66258












          • Is there a way to handle both Ctrl+C and a usual exit in the same place? Or do I have to write two identical handlers?
            – Erel Segal-Halevi
            Dec 25 '12 at 20:49










          • Just as a note, if you have to end node by a kill command doing kill -2 will pass the SIGINT code. We have to do it this way because we have node logging to a txt file so Ctrl + C is not possible.
            – Aust
            Feb 14 '13 at 23:22


















          • Is there a way to handle both Ctrl+C and a usual exit in the same place? Or do I have to write two identical handlers?
            – Erel Segal-Halevi
            Dec 25 '12 at 20:49










          • Just as a note, if you have to end node by a kill command doing kill -2 will pass the SIGINT code. We have to do it this way because we have node logging to a txt file so Ctrl + C is not possible.
            – Aust
            Feb 14 '13 at 23:22
















          Is there a way to handle both Ctrl+C and a usual exit in the same place? Or do I have to write two identical handlers?
          – Erel Segal-Halevi
          Dec 25 '12 at 20:49




          Is there a way to handle both Ctrl+C and a usual exit in the same place? Or do I have to write two identical handlers?
          – Erel Segal-Halevi
          Dec 25 '12 at 20:49












          Just as a note, if you have to end node by a kill command doing kill -2 will pass the SIGINT code. We have to do it this way because we have node logging to a txt file so Ctrl + C is not possible.
          – Aust
          Feb 14 '13 at 23:22




          Just as a note, if you have to end node by a kill command doing kill -2 will pass the SIGINT code. We have to do it this way because we have node logging to a txt file so Ctrl + C is not possible.
          – Aust
          Feb 14 '13 at 23:22











          8














          This catches every exit event I can find that can be handled. Seems quite reliable and clean so far.



          [`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((eventType) => {
          process.on(eventType, cleanUpServer.bind(null, eventType));
          })





          share|improve this answer


























            8














            This catches every exit event I can find that can be handled. Seems quite reliable and clean so far.



            [`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((eventType) => {
            process.on(eventType, cleanUpServer.bind(null, eventType));
            })





            share|improve this answer
























              8












              8








              8






              This catches every exit event I can find that can be handled. Seems quite reliable and clean so far.



              [`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((eventType) => {
              process.on(eventType, cleanUpServer.bind(null, eventType));
              })





              share|improve this answer












              This catches every exit event I can find that can be handled. Seems quite reliable and clean so far.



              [`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((eventType) => {
              process.on(eventType, cleanUpServer.bind(null, eventType));
              })






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Mar 20 '18 at 19:29









              light24bulbslight24bulbs

              7701922




              7701922























                  5














                  Just wanted to mention death package here: https://github.com/jprichardson/node-death



                  Example:



                  var ON_DEATH = require('death')({uncaughtException: true}); //this is intentionally ugly

                  ON_DEATH(function(signal, err) {
                  //clean up code here
                  })





                  share|improve this answer


























                    5














                    Just wanted to mention death package here: https://github.com/jprichardson/node-death



                    Example:



                    var ON_DEATH = require('death')({uncaughtException: true}); //this is intentionally ugly

                    ON_DEATH(function(signal, err) {
                    //clean up code here
                    })





                    share|improve this answer
























                      5












                      5








                      5






                      Just wanted to mention death package here: https://github.com/jprichardson/node-death



                      Example:



                      var ON_DEATH = require('death')({uncaughtException: true}); //this is intentionally ugly

                      ON_DEATH(function(signal, err) {
                      //clean up code here
                      })





                      share|improve this answer












                      Just wanted to mention death package here: https://github.com/jprichardson/node-death



                      Example:



                      var ON_DEATH = require('death')({uncaughtException: true}); //this is intentionally ugly

                      ON_DEATH(function(signal, err) {
                      //clean up code here
                      })






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 12 '16 at 19:38









                      antongorodezkiyantongorodezkiy

                      1,47022030




                      1,47022030























                          5














                          function fnAsyncTest(callback) {
                          require('fs').writeFile('async.txt', 'bye!', callback);
                          }

                          function fnSyncTest() {
                          for (var i = 0; i < 10; i++) {}
                          }

                          function killProcess() {

                          if (process.exitTimeoutId) {
                          return;
                          }

                          process.exitTimeoutId = setTimeout(process.exit, 5000);
                          console.log('process will exit in 5 seconds');

                          fnAsyncTest(function() {
                          console.log('async op. done', arguments);
                          });

                          if (!fnSyncTest()) {
                          console.log('sync op. done');
                          }
                          }

                          // https://nodejs.org/api/process.html#process_signal_events
                          process.on('SIGTERM', killProcess);
                          process.on('SIGINT', killProcess);

                          process.on('uncaughtException', function(e) {

                          console.log('[uncaughtException] app will be terminated: ', e.stack);

                          killProcess();
                          /**
                          * @https://nodejs.org/api/process.html#process_event_uncaughtexception
                          *
                          * 'uncaughtException' should be used to perform synchronous cleanup before shutting down the process.
                          * It is not safe to resume normal operation after 'uncaughtException'.
                          * If you do use it, restart your application after every unhandled exception!
                          *
                          * You have been warned.
                          */
                          });

                          console.log('App is running...');
                          console.log('Try to press CTRL+C or SIGNAL the process with PID: ', process.pid);

                          process.stdin.resume();
                          // just for testing





                          share|improve this answer



















                          • 1




                            This answer deserves all the glory, but because there is no explanation, there is no up-vote either unfortunately. What significant about this answer is, the doc says, "Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. ", and this answer overcomes that limitation!
                            – xpt
                            Feb 25 '18 at 14:36
















                          5














                          function fnAsyncTest(callback) {
                          require('fs').writeFile('async.txt', 'bye!', callback);
                          }

                          function fnSyncTest() {
                          for (var i = 0; i < 10; i++) {}
                          }

                          function killProcess() {

                          if (process.exitTimeoutId) {
                          return;
                          }

                          process.exitTimeoutId = setTimeout(process.exit, 5000);
                          console.log('process will exit in 5 seconds');

                          fnAsyncTest(function() {
                          console.log('async op. done', arguments);
                          });

                          if (!fnSyncTest()) {
                          console.log('sync op. done');
                          }
                          }

                          // https://nodejs.org/api/process.html#process_signal_events
                          process.on('SIGTERM', killProcess);
                          process.on('SIGINT', killProcess);

                          process.on('uncaughtException', function(e) {

                          console.log('[uncaughtException] app will be terminated: ', e.stack);

                          killProcess();
                          /**
                          * @https://nodejs.org/api/process.html#process_event_uncaughtexception
                          *
                          * 'uncaughtException' should be used to perform synchronous cleanup before shutting down the process.
                          * It is not safe to resume normal operation after 'uncaughtException'.
                          * If you do use it, restart your application after every unhandled exception!
                          *
                          * You have been warned.
                          */
                          });

                          console.log('App is running...');
                          console.log('Try to press CTRL+C or SIGNAL the process with PID: ', process.pid);

                          process.stdin.resume();
                          // just for testing





                          share|improve this answer



















                          • 1




                            This answer deserves all the glory, but because there is no explanation, there is no up-vote either unfortunately. What significant about this answer is, the doc says, "Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. ", and this answer overcomes that limitation!
                            – xpt
                            Feb 25 '18 at 14:36














                          5












                          5








                          5






                          function fnAsyncTest(callback) {
                          require('fs').writeFile('async.txt', 'bye!', callback);
                          }

                          function fnSyncTest() {
                          for (var i = 0; i < 10; i++) {}
                          }

                          function killProcess() {

                          if (process.exitTimeoutId) {
                          return;
                          }

                          process.exitTimeoutId = setTimeout(process.exit, 5000);
                          console.log('process will exit in 5 seconds');

                          fnAsyncTest(function() {
                          console.log('async op. done', arguments);
                          });

                          if (!fnSyncTest()) {
                          console.log('sync op. done');
                          }
                          }

                          // https://nodejs.org/api/process.html#process_signal_events
                          process.on('SIGTERM', killProcess);
                          process.on('SIGINT', killProcess);

                          process.on('uncaughtException', function(e) {

                          console.log('[uncaughtException] app will be terminated: ', e.stack);

                          killProcess();
                          /**
                          * @https://nodejs.org/api/process.html#process_event_uncaughtexception
                          *
                          * 'uncaughtException' should be used to perform synchronous cleanup before shutting down the process.
                          * It is not safe to resume normal operation after 'uncaughtException'.
                          * If you do use it, restart your application after every unhandled exception!
                          *
                          * You have been warned.
                          */
                          });

                          console.log('App is running...');
                          console.log('Try to press CTRL+C or SIGNAL the process with PID: ', process.pid);

                          process.stdin.resume();
                          // just for testing





                          share|improve this answer














                          function fnAsyncTest(callback) {
                          require('fs').writeFile('async.txt', 'bye!', callback);
                          }

                          function fnSyncTest() {
                          for (var i = 0; i < 10; i++) {}
                          }

                          function killProcess() {

                          if (process.exitTimeoutId) {
                          return;
                          }

                          process.exitTimeoutId = setTimeout(process.exit, 5000);
                          console.log('process will exit in 5 seconds');

                          fnAsyncTest(function() {
                          console.log('async op. done', arguments);
                          });

                          if (!fnSyncTest()) {
                          console.log('sync op. done');
                          }
                          }

                          // https://nodejs.org/api/process.html#process_signal_events
                          process.on('SIGTERM', killProcess);
                          process.on('SIGINT', killProcess);

                          process.on('uncaughtException', function(e) {

                          console.log('[uncaughtException] app will be terminated: ', e.stack);

                          killProcess();
                          /**
                          * @https://nodejs.org/api/process.html#process_event_uncaughtexception
                          *
                          * 'uncaughtException' should be used to perform synchronous cleanup before shutting down the process.
                          * It is not safe to resume normal operation after 'uncaughtException'.
                          * If you do use it, restart your application after every unhandled exception!
                          *
                          * You have been warned.
                          */
                          });

                          console.log('App is running...');
                          console.log('Try to press CTRL+C or SIGNAL the process with PID: ', process.pid);

                          process.stdin.resume();
                          // just for testing






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 8 '18 at 8:20

























                          answered Feb 2 '16 at 18:26









                          Abdullah AydınAbdullah Aydın

                          583512




                          583512








                          • 1




                            This answer deserves all the glory, but because there is no explanation, there is no up-vote either unfortunately. What significant about this answer is, the doc says, "Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. ", and this answer overcomes that limitation!
                            – xpt
                            Feb 25 '18 at 14:36














                          • 1




                            This answer deserves all the glory, but because there is no explanation, there is no up-vote either unfortunately. What significant about this answer is, the doc says, "Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. ", and this answer overcomes that limitation!
                            – xpt
                            Feb 25 '18 at 14:36








                          1




                          1




                          This answer deserves all the glory, but because there is no explanation, there is no up-vote either unfortunately. What significant about this answer is, the doc says, "Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. ", and this answer overcomes that limitation!
                          – xpt
                          Feb 25 '18 at 14:36




                          This answer deserves all the glory, but because there is no explanation, there is no up-vote either unfortunately. What significant about this answer is, the doc says, "Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. ", and this answer overcomes that limitation!
                          – xpt
                          Feb 25 '18 at 14:36











                          0














                          io.js has an exit and a beforeExit event, which do what you want.






                          share|improve this answer


























                            0














                            io.js has an exit and a beforeExit event, which do what you want.






                            share|improve this answer
























                              0












                              0








                              0






                              io.js has an exit and a beforeExit event, which do what you want.






                              share|improve this answer












                              io.js has an exit and a beforeExit event, which do what you want.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jan 31 '15 at 15:53









                              Golo RodenGolo Roden

                              57.6k59209304




                              57.6k59209304























                                  -1














                                  In the case where the process was spawned by another node process, like:



                                  var child = spawn('gulp', ['watch'], {
                                  stdio: 'inherit',
                                  });


                                  And you try to kill it later, via:



                                  child.kill();


                                  This is how you handle the event [on the child]:



                                  process.on('SIGTERM', function() {
                                  console.log('Goodbye!');
                                  });





                                  share|improve this answer


























                                    -1














                                    In the case where the process was spawned by another node process, like:



                                    var child = spawn('gulp', ['watch'], {
                                    stdio: 'inherit',
                                    });


                                    And you try to kill it later, via:



                                    child.kill();


                                    This is how you handle the event [on the child]:



                                    process.on('SIGTERM', function() {
                                    console.log('Goodbye!');
                                    });





                                    share|improve this answer
























                                      -1












                                      -1








                                      -1






                                      In the case where the process was spawned by another node process, like:



                                      var child = spawn('gulp', ['watch'], {
                                      stdio: 'inherit',
                                      });


                                      And you try to kill it later, via:



                                      child.kill();


                                      This is how you handle the event [on the child]:



                                      process.on('SIGTERM', function() {
                                      console.log('Goodbye!');
                                      });





                                      share|improve this answer












                                      In the case where the process was spawned by another node process, like:



                                      var child = spawn('gulp', ['watch'], {
                                      stdio: 'inherit',
                                      });


                                      And you try to kill it later, via:



                                      child.kill();


                                      This is how you handle the event [on the child]:



                                      process.on('SIGTERM', function() {
                                      console.log('Goodbye!');
                                      });






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Apr 20 '16 at 23:12









                                      Jaime GómezJaime Gómez

                                      5,63432831




                                      5,63432831






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14031763%2fdoing-a-cleanup-action-just-before-node-js-exits%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Berounka

                                          Sphinx de Gizeh

                                          Different font size/position of beamer's navigation symbols template's content depending on regular/plain...