TBE
TBE

Reputation: 1133

Debugging a graceful shutdown on node.js

I have the following code in my app.js:

process.stdin.resume();//so the program will not close instantly

//do something when app is closing
process.on('exit',exitHandler.bind(null,{exit:true,event: "exit"}));

//catches uncaught exceptions
process.on('uncaughtException',exitHandler.bind(null, {exit:false,event: "uncaughtException"}));

I read all that there is to read about gracefully shutting down node.js server but couldn't find anything about how to debug it.

The problem is that must IDE's terminated/kill the node process when you click on the "Stop" button in the debug console.

Does anyone have an idea on how can i debug my graceful shutdown code? the debug mode never stops on breakpoints inside exitHandler when shutting down the debug session.

I'm using WebStorm, but i read that the same probably happens on other IDEs as well.

Thanks

Upvotes: 4

Views: 2158

Answers (1)

Meredian
Meredian

Reputation: 990

Well, there's no magic. To get 'exit' event your code must eventually hit process.exit() code, and to get 'uncaughtException' you need to raise unhandled exception.

Maybe there is an insane way to trigger this code without creating actual events, but you should stick to normal program lifecycle, because that's how things work in production - and that's definitely what you want to test.

To practice: If you want to see once if you're correct, you can just manually add proper code just to your app, so it will be triggered once it is loaded:

setTimeout(function() {
    process.exit(1);
    // or throw new Error("Uncaught exception");
}, 2000);

Debug, then remove.

If you're planning to somehow integrate this into some tests, you need to keep following behavior within code, and add a way to trigger it:

.... // when app is loaded
if (process.env.NODE_TEST_TRIGGER_PROCESS_EXIT) {
    process.exit(1);
}

And add an execution scenario to run it with proper option:

$ NODE_TEST_TRIGGER_PROCESS_EXIT=true node myapp.js

UPD: If you really don't care about different events, check other signals: https://nodejs.org/api/process.html#process_signal_events Maybe app will receive SIGINT or SIGTERM. But if it's SIGKILL, you still can't catch it, so you have to create event yourself.

Upvotes: 2

Related Questions