Adding an event layer to your modules
Now that we know how to use the EventEmitter
class, let’s add an event layer to our modules. In this example, we will create a module that will be used to save files and emit an event every time a file change is saved.
Let’s create a file called utils.mjs
and add the following code:
import { writeFile } from 'node:fs/promises'; import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); const on = emitter.on.bind(emitter); const save = async (location, data) => { await writeFile(location, data); emitter.emit('file:saved', { location, data }); }; export { save, on };
In this example, we created an instance of the EventEmitter
class and exported the save
function. This function will be used to save the file and emit the file:saved
event. Then, we export the on
method of the EventEmitter
class. This method will be used to register event listeners for...