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.
In this JavaScript version:
We use the
process
object from Node.js, which provides similar functionality to signal handling in Unix-like systems.Instead of channels, we use a
Promise
to handle the asynchronous nature of signal reception.We register event listeners for ‘SIGINT’ and ‘SIGTERM’ using
process.on()
. These are similar to the signals we handled in the original example.The main function creates a Promise that resolves when a signal is received, then waits for this Promise to resolve before exiting.
When a signal is received, we log it and resolve the Promise, which then leads to the program exiting.
To run this program:
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.