Beginner
cli
Handling OS Signals
You can listen for OS signals using the `Deno.addSignalListener` function. This allows you to do things like gracefully shutdown a server when a `SIGINT` signal is received.
!--frsh-copybutton:1-->
console.log("Counting seconds...");
let i = 0;
We isolate the signal handler function so that we can remove it later.
!--frsh-copybutton:2-->
function sigIntHandler() {
console.log("interrupted! your number was", i);
Deno.exit();
}
Then, we can listen for the `SIGINT` signal, which is sent when the user presses Ctrl+C.
!--frsh-copybutton:3-->
Deno.addSignalListener("SIGINT", sigIntHandler);
While we're waiting for the signal, we can do other things, like count seconds, or start a server.
!--frsh-copybutton:4-->
const interval = setInterval(() => {
i++;
}, 1000);
And, after 10 seconds, we can exit and remove the signal listener.
!--frsh-copybutton:5-->
setTimeout(() => {
clearInterval(interval);
Deno.removeSignalListener("SIGINT", sigIntHandler);
console.log("done! it has been 10 seconds");
}, 10_000);
Run this example locally using the Deno CLI:
deno run https://byexample-wwv03xf36j0g.deno.dev/os-signals.ts
Additional resources: