How to perform an async operation on exit

18,348

Solution 1

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.

Solution 2

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
});

Solution 3

Here's my take on this. A bit long to post as a code snippet in here, so sharing a Github gist.

https://gist.github.com/nfantone/1eaa803772025df69d07f4dbf5df7e58

It's pretty straightforward. You use it like so:

'use strict';
const beforeShutdown = require('./before-shutdown');

// Register shutdown callbacks: they will be executed in the order they were provided
beforeShutdown(() => db.close());
beforeShutdown(() => server.close());
beforeShutdown(/* Do any async cleanup */);

The above will listen for a certain set of system signals (SIGINT, a.k.a Ctrl + C, and SIGTERM by default) and call each handler in order before shutting down the whole process.

It also,

  • Supports async callbacks (or returning a Promise).
  • Warns about failing shutdown handlers, but prevents the error/rejection from bubbling up.
  • Forces shutdown if handlers do not return after some time (15 seconds, by default).
  • Callbacks can be registered from any module in your code base.

Solution 4

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(+evtOrExitCodeOrError) ? 1 : +evtOrExitCodeOrError);
}

[
  'beforeExit', 'uncaughtException', 'unhandledRejection', 
  'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 
  'SIGABRT','SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 
  'SIGUSR2', 'SIGTERM', 
].forEach(evt => process.on(evt, exitHandler));
Share:
18,348
Kesem David
Author by

Kesem David

Updated on June 17, 2022

Comments

  • Kesem David
    Kesem David almost 2 years

    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?

  • Kesem David
    Kesem David over 7 years
    Hey Ben, thanks for your answer. Could you provide some more explanation about this code? the signals im familiar with are SIGINT and exit, what are the others? also, why are u checking if the sig is a string? and assuming the db.close is async it wont be finished there right?
  • Ben
    Ben over 5 years
    To be honest, I don't know since I haven't use Windows for over a decade but I think it should work because this is standard node.js code. Node.js on Windows should know how to interpret it.
  • Nicolás Fantone
    Nicolás Fantone over 3 years
    @KesemDavid is actually right here. In the (very likely) event that db.close() is async, calling if from an 'exit' event handler does not guarantee its execution. Checkout some of the answers below for more rigorous implementations of this.
  • Alexey Grinko
    Alexey Grinko over 3 years
    They say in the docs that 'beforeExit' is not emitted when process.exit() is explicitly called somewhere in the code, or when unaught exceptions happen, which makes its usage quite limited. Source: nodejs.org/api/process.html#process_event_beforeexit
  • Nick Bull
    Nick Bull about 3 years
    Is SIGILL meant to be SIGKILL?
  • darcyparker
    darcyparker over 2 years
    As @NicolásFantone mentioned, the event handler is sync. The reference he linked says "Listener functions must only perform synchronous operations." Your terminator fn is called, but it is not guaranteed to execute the async work to completion.
  • darcyparker
    darcyparker over 2 years
    Can you clarify how it supports async callbacks? Your gist relies on process.once() . The handler for process.once('SIGTERM', handler) is a sync function. I am sure the async callback is called, but it is not guaranteed to run until its returned promise is fullfilled. Do you have tests showing it will?
  • LeoPucciBr
    LeoPucciBr over 2 years
    Didn´t you forgot the exit event?
  • Ron S.
    Ron S. over 2 years
    @LeoPucciBr I believe beforeExit has that path covered