How to perform an async operation on exit

2020-08-09 05:57发布

I've been trying to perform an asynchronous operation before my process is terminated.

Saying 'terminated' I mean every possibility of termination:

  • ctrl+c
  • Uncaught exception
  • Crashes
  • End of code
  • Anything..

To my knowledge the exit event does that but for synchronous operations.

Reading the Nodejs docs i found the beforeExit event is for the async operations BUT :

The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions.

The 'beforeExit' should not be used as an alternative to the 'exit' event unless the intention is to schedule additional work.

Any suggestions?

3条回答
Lonely孤独者°
2楼-- · 2020-08-09 06:06

You can trap the signals and perform your async task before exiting. Something like this will call terminator() function before exiting (even javascript error in the code):

process.on('exit', function () {
    // Do some cleanup such as close db
    if (db) {
        db.close();
    }
});

// catching signals and do something 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 your async task here and then call process.exit() after async task is 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 from node's documentation, this link refers to standard POSIX signal names
  • The signals should be string. However, I've seen others have done the check so there might be some other unexpected signals that I don't know about. Just want to make sure before calling process.exit(). I figure it doesn't take much time to do the check anyway.
  • for db.close(), I guess it depends on the driver you are using. Whether it's sync of async. Even if it's async, and you don't need to do anything after db closed, then it should be fine because async db.close() just emits close event and the event loop would continue to process it whether your server exited or not.
查看更多
疯言疯语
3楼-- · 2020-08-09 06:12

Combining answers + handling for uncaught exceptions and promise rejections

async function exitHandler(evtOrExitCodeOrError: number | string | Error) {
  try {
    // await async code here
    // Optionally: Handle evtOrExitCodeOrError here
  } catch (e) {
    console.error('EXIT HANDLER ERROR', e);
  }

  process.exit(isNaN(+evtOrExitCode) ? 1 : +evtOrExitCode);
}

[
  'beforeExit', 'uncaughtException', 'unhandledRejection', 
  'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 
  'SIGABRT','SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 
  'SIGUSR2', 'SIGTERM', 
].forEach(evt => process.on(evt, exitHandler));
查看更多
Bombasti
4楼-- · 2020-08-09 06:27

Using beforeExit hook

The 'beforeExit' event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when there is no work scheduled, but a listener registered on the 'beforeExit' event can make asynchronous calls, and thereby cause the Node.js process to continue.

process.on('beforeExit', async () => {
    await something()
    process.exit(0) // if you don't close yourself this will run forever
});
查看更多
登录 后发表回答