I am writing my first Koa app, and need to close my DB connection and do some other cleanup before the application exits.
I tried adding the code:
function cleanup() {
console.log('Closing...');
}
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
And if I press clrl-c on the console, the app does exit and my cleanup function is called, but a process continues to run and keep the port in use, so I can't re-run my app. The cleanup function does nothing at the moment, it just does a console.log() statement and nothing else.
Attempting to re-run the app just results in the error:
Error: listen EADDRINUSE :::8888
If I comment out the process.on() lines, then the app does release its port correctly.
Is there a better/correct way to detect app exit and perform cleanup?
Update: The ports are eventually released after some length of time. Perhaps it waits for the socket timeout?
Using process.on('exit', ...) instead seems to resolve this issue.
Update2: Strangely Nodejs was running old code (I could comment out entire files and re-run node, and it would still execute fine as if my code had not been edited) so my previous comment turned out to not be true.
process.on('exit', cleanup);
the cleanup function is never called. It seems like this event is never triggered if ctrl-c is pressed on the console (Windows. Haven't tried on OSX yet).
SIGTERM and SIGINT have default handlers on non-Windows platforms that resets the terminal mode before exiting with code 128 + signal number. If one of these signals has a listener installed, its default behavior will be removed (Node.js will no longer exit).
maybe you should add process.exit(1) in your cleanup function.
It looks like this code works:
function cleanup() {
console.log('Closing...');
process.exit(1);
}
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
Thanks for the help @dead-horse
Most helpful comment
It looks like this code works:
Thanks for the help @dead-horse