Doing a cleanup action just before Node.js exits

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

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

提交回复
热议问题