Signals in TypeScript
This program demonstrates how to handle signals in TypeScript. Here’s the full source code:
Let’s break down this code:
We import the
process
module, which provides information about, and control over, the current Node.js process.In the
main
function, we create aPromise
that will resolve when a signal is received.We use
process.on()
to register handlers forSIGINT
andSIGTERM
signals. When either of these signals is received, we log a message and resolve the promise.We log a message indicating that the program is waiting for a signal.
We use
Promise.then()
to wait for the signal promise to resolve. When it does, we log an “Exiting” message and exit the process.
To run this program:
- Save the code in a file named
signals.ts
. - Make sure you have TypeScript and ts-node installed (
npm install -g typescript ts-node
). - Run the program using ts-node:
The program will now wait for a signal. You can send a SIGINT signal by pressing Ctrl+C in the terminal:
This example demonstrates how to handle signals in a TypeScript Node.js application. It’s important to note that while this approach works in a Node.js environment, TypeScript itself doesn’t have built-in signal handling as it’s primarily a compile-time language. The actual signal handling is provided by Node.js, which TypeScript is running on top of.
In a real-world scenario, you might use this pattern to gracefully shut down a server or clean up resources when the application receives a termination signal.