The Node.js event emitter library
Now that we know how to watch for file changes, let’s explore the Node.js events library. This library provides an EventEmitter
class that can be used to build simple interface to register and unregister event listeners and emit events.
Let’s create a file called event-emitter.mjs
and add the following code:
import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.on('message', (message) => { console.log(`Message received: ${message}`); }); emitter.emit('message', 'Hello world!');
In this example, we created an instance of the EventEmitter
class and registered an event listener for the message
event. Then, we emit the message
event with the message Hello world!
. If you run the script, you will see that the message is printed in the console.
You can also register multiple event listeners and emitters for the same event; this is...