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:

  1. We import the process module, which provides information about, and control over, the current Node.js process.

  2. In the main function, we create a Promise that will resolve when a signal is received.

  3. We use process.on() to register handlers for SIGINT and SIGTERM signals. When either of these signals is received, we log a message and resolve the promise.

  4. We log a message indicating that the program is waiting for a signal.

  5. 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:

  1. Save the code in a file named signals.ts.
  2. Make sure you have TypeScript and ts-node installed (npm install -g typescript ts-node).
  3. 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.