summaryrefslogtreecommitdiff
path: root/std/signal/mod.ts
diff options
context:
space:
mode:
authorChris Knight <cknight1234@gmail.com>2020-04-10 15:05:56 +0100
committerGitHub <noreply@github.com>2020-04-10 10:05:56 -0400
commit5bf1e4de3b394eef203be3c393db57538e748be1 (patch)
treee45ab50e56bc07512c2071dead3b2dda9716c030 /std/signal/mod.ts
parent02bc58d83253fd3be61787bb28b6b02e3aa71092 (diff)
feat(std/signal): add utility for listening to signal events (#4696)
Diffstat (limited to 'std/signal/mod.ts')
-rw-r--r--std/signal/mod.ts46
1 files changed, 45 insertions, 1 deletions
diff --git a/std/signal/mod.ts b/std/signal/mod.ts
index 0f2b47534..a463142e6 100644
--- a/std/signal/mod.ts
+++ b/std/signal/mod.ts
@@ -1,8 +1,28 @@
import { MuxAsyncIterator } from "../util/async.ts";
+export type Disposable = { dispose: () => void };
+
+/**
+ * Generates an AsyncIterable which can be awaited on for one or more signals.
+ * `dispose()` can be called when you are finished waiting on the events.
+ *
+ * Example:
+ *
+ * const sig = signal(Deno.Signal.SIGUSR1, Deno.Signal.SIGINT);
+ * setTimeout(() => {}, 5000); // Prevents exiting immediately
+ *
+ * for await (const _ of sig) {
+ * console.log("interrupt or usr1 signal received");
+ * }
+ *
+ * // At some other point in your code when finished listening:
+ * sig.dispose();
+ *
+ * @param signos - one or more `Deno.Signal`s to await on
+ */
export function signal(
...signos: [number, ...number[]]
-): AsyncIterable<void> & { dispose: () => void } {
+): AsyncIterable<void> & Disposable {
const mux = new MuxAsyncIterator<void>();
if (signos.length < 1) {
@@ -26,3 +46,27 @@ export function signal(
return Object.assign(mux, { dispose });
}
+
+/**
+ * Registers a callback function to be called on triggering of a signal event.
+ *
+ * const handle = onSignal(Deno.Signal.SIGINT, () => {
+ * console.log('Received SIGINT');
+ * handle.dispose(); // de-register from receiving further events
+ * });
+ *
+ * @param signo One of Deno.Signal (e.g. Deno.Signal.SIGINT)
+ * @param callback Callback function triggered upon signal event
+ */
+export function onSignal(signo: number, callback: () => void): Disposable {
+ const sig = signal(signo);
+
+ //setTimeout allows `sig` to be returned before blocking on the await
+ setTimeout(async () => {
+ for await (const _ of sig) {
+ callback();
+ }
+ }, 0);
+
+ return sig;
+}