import { addShutdownListener } from "https://deno.land/x/ayonli_jsext@v0.9.72/runtime.ts";
Adds a listener function to be called when the program receives a SIGINT
(Ctrl+C
) signal, or a shutdown
message sent by the parent process (a
PM2 pattern for Windows), so that the program can perform a graceful
shutdown.
This function can be called multiple times to register multiple listeners, they will be executed in the order they were added, and any asynchronous listener will be awaited before the next listener is executed.
Inside the listener, there is no need to call process.exit
or Deno.exit
,
the program will exit automatically after all listeners are executed in order.
In fact, calling the exit
method in a listener is problematic and will
cause any subsequent listeners not to be executed.
The listener function receives a CloseEvent, if we don't what the program
to exit, we can call event.preventDefault()
to prevent from exiting.
In the browser or unsupported environments, this function is a no-op.
Examples
Example 1
Example 1
import { addShutdownListener } from "@ayonli/jsext/runtime";
import { serve } from "@ayonli/jsext/http";
const server = serve({
fetch(req) {
return new Response("Hello, World!");
}
});
addShutdownListener(async () => {
await server.close();
});