Doing a cleanup action just before Node.js exits

后端 未结 11 1553
时光说笑
时光说笑 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:09

    After playing around with other answer, here is my solution for this task. Implementing this way helps me centralize cleanup in one place, preventing double handling the cleanup.

    1. I would like to route all other exiting codes to 'exit' code.
    const others = [`SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`]
    others.forEach((eventType) => {
        process.on(eventType, exitRouter.bind(null, { exit: true }));
    })
    
    1. What the exitRouter does is calling process.exit()
    function exitRouter(options, exitCode) {
       if (exitCode || exitCode === 0) console.log(`ExitCode ${exitCode}`);
       if (options.exit) process.exit();
    }
    
    1. On 'exit', handle the clean up with a new function
    function exitHandler(exitCode) {
      console.log(`ExitCode ${exitCode}`);
      console.log('Exiting finally...')
    }
    
    process.on('exit', exitHandler)
    

    For the demo purpose, this is link to my gist. In the file, i add a setTimeout to fake the process running.

    If you run node node-exit-demo.js and do nothing, then after 2 seconds, you see the log:

    The service is finish after a while.
    ExitCode 0
    Exiting finally...
    

    Else if before the service finish, you terminate by ctrl+C, you'll see:

    ^CExitCode SIGINT
    ExitCode 0
    Exiting finally...
    

    What happened is the Node process exited initially with code SIGINT, then it routes to process.exit() and finally exited with exit code 0.

提交回复
热议问题