Signals in TypeScript
This program demonstrates how to handle signals in TypeScript. Here’s the full source code:
import * as process from 'process';
function main() {
// Create a Promise to handle the signal
const signalPromise = new Promise<void>((resolve) => {
// Register signal handlers for SIGINT and SIGTERM
process.on('SIGINT', () => {
console.log('\nReceived SIGINT');
resolve();
});
process.on('SIGTERM', () => {
console.log('\nReceived SIGTERM');
resolve();
});
});
console.log('Awaiting signal...');
// Wait for a signal
signalPromise.then(() => {
console.log('Exiting');
process.exit(0);
});
}
main();
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:
$ ts-node signals.ts
Awaiting signal...
The program will now wait for a signal. You can send a SIGINT signal by pressing Ctrl+C in the terminal:
$ ts-node signals.ts
Awaiting signal...
^C
Received SIGINT
Exiting
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.