Doing a cleanup action just before Node.js exits

后端 未结 11 1556
时光说笑
时光说笑 2020-11-22 13:54

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

I tried th

11条回答
  •  再見小時候
    2020-11-22 14:03

    "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.

提交回复
热议问题