Signals in JavaScript

Here’s the translation of the Go code to JavaScript, with explanations in Markdown format suitable for Hugo:

Our program demonstrates how to handle signals in JavaScript. Since JavaScript doesn’t have direct equivalents for Unix signals, we’ll use the process object in Node.js to simulate similar behavior.

const process = require('process');

function main() {
    // We'll use process.on to listen for specific events
    // that are similar to Unix signals

    // Create a Promise that resolves when a signal is received
    const signalPromise = new Promise((resolve) => {
        // Listen for SIGINT (Ctrl+C)
        process.on('SIGINT', () => {
            console.log();
            console.log('SIGINT');
            resolve('SIGINT');
        });

        // Listen for SIGTERM
        process.on('SIGTERM', () => {
            console.log();
            console.log('SIGTERM');
            resolve('SIGTERM');
        });
    });

    console.log("awaiting signal");

    // Wait for the Promise to resolve when a signal is received
    signalPromise.then((signal) => {
        console.log("exiting");
        process.exit(0);
    });
}

main();

In this JavaScript version:

  1. We use the process object from Node.js, which provides similar functionality to signal handling in Unix-like systems.

  2. Instead of channels, we use a Promise to handle the asynchronous nature of signal reception.

  3. We register event listeners for ‘SIGINT’ and ‘SIGTERM’ using process.on(). These are similar to the signals we handled in the original example.

  4. The main function creates a Promise that resolves when a signal is received, then waits for this Promise to resolve before exiting.

  5. When a signal is received, we log it and resolve the Promise, which then leads to the program exiting.

To run this program:

$ node signals.js
awaiting signal
^C
SIGINT
exiting

When we run this program, it will block waiting for a signal. By typing ctrl-C (which the terminal shows as ^C), we can send a SIGINT signal, causing the program to print SIGINT and then exit.

Note that this example uses Node.js features and won’t work in a browser environment. In a browser, you would typically use different methods to handle things like page unload or visibility changes.