2020-05-06 18:21:13 -04:00
|
|
|
## Handle OS Signals
|
|
|
|
|
|
|
|
> This program makes use of an unstable Deno feature. Learn more about
|
2020-05-09 09:15:26 -04:00
|
|
|
> [unstable features](../runtime/stability.md).
|
2020-05-06 18:21:13 -04:00
|
|
|
|
2020-07-23 10:05:36 -04:00
|
|
|
[API Reference](https://doc.deno.land/https/raw.githubusercontent.com/denoland/deno/master/cli/dts/lib.deno.unstable.d.ts#Deno.signal)
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
You can use `Deno.signal()` function for handling OS signals.
|
|
|
|
|
2020-05-13 23:54:57 -04:00
|
|
|
```ts
|
2020-05-06 18:21:13 -04:00
|
|
|
for await (const _ of Deno.signal(Deno.Signal.SIGINT)) {
|
|
|
|
console.log("interrupted!");
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
`Deno.signal()` also works as a promise.
|
|
|
|
|
2020-05-13 23:54:57 -04:00
|
|
|
```ts
|
2020-05-14 16:18:33 -04:00
|
|
|
await Deno.signal(Deno.Signal.SIGINT);
|
2020-05-06 18:21:13 -04:00
|
|
|
console.log("interrupted!");
|
|
|
|
```
|
|
|
|
|
|
|
|
If you want to stop watching the signal, you can use `dispose()` method of the
|
|
|
|
signal object.
|
|
|
|
|
2020-05-13 23:54:57 -04:00
|
|
|
```ts
|
2020-05-06 18:21:13 -04:00
|
|
|
const sig = Deno.signal(Deno.Signal.SIGINT);
|
2020-05-13 23:54:57 -04:00
|
|
|
setTimeout(() => {
|
|
|
|
sig.dispose();
|
|
|
|
}, 5000);
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
for await (const _ of sig) {
|
|
|
|
console.log("interrupted");
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
The above for-await loop exits after 5 seconds when sig.dispose() is called.
|