Sometimes, we want to detect CTRL+C key press in Node.js.
In this article, we’ll look at how to detect CTRL+C key press in Node.js.
How to detect CTRL+C key press in Node.js?
To detect CTRL+C key press in Node.js, we can call process.on
with 'SIGINT'
.
For instance, we write
process.on('SIGINT', () => {
console.log("Caught interrupt signal");
if (shouldExit) {
process.exit();
}
});
to call process.on
with 'SIGINT'
to listen for ctrl+c key press.
The interrupt signal is triggered by ctrl+c.
In the callback, we call process.exit
to exit the app if shouldExit
is true
.
Conclusion
To detect CTRL+C key press in Node.js, we can call process.on
with 'SIGINT'
.