Erel Segal-Halevi Erel Segal-Halevi - 1 year ago 164
Node.js Question

doing a cleanup action just before node.js exits

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

I tried this:

process.on('exit', function (){

Started the process, killed it, and nothing happened; started again, pressed Ctrl+C, and still nothing happened...

Answer Source


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, err) {
    if (options.cleanup) console.log('clean');
    if (err) console.log(err.stack);
    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 uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit:true}));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download