In Node.js, the EventEmitter
class is a core module that facilitates communication between objects in a publisher-subscriber pattern. It allows for the implementation of event-driven architectures, where certain parts of the code can emit events, and other parts can listen for and respond to those events. The EventEmitter
enables decoupling of different parts of an application, making it easier to build scalable and modular systems.
Here's a brief overview of how the EventEmitter
works:
1.Event Subscription: You can create an instance of EventEmitter
and use the on
method to subscribe to events.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
2.Event Emission: You can use the emit
method to trigger an event.
`myEmitter.emit('event');`
3.Passing Data with Events: You can pass data along with events to provide context or additional information.
myEmitter.on('dataEvent', (data) => {console.log('Received data:', data); }); myEmitter.emit('dataEvent', { key: 'value' });
4.Error Events: The EventEmitter
also has special support for error events, allowing you to handle errors more effectively in asynchronous code.
myEmitter.on('error', (err) => { console.error('Error occurred:', err); }); myEmitter.emit('error', new Error('Something went wrong'));
The EventEmitter
is the foundation for many of the asynchronous operations in Node.js, such as handling HTTP requests, file I/O, and other events. It enables developers to create robust and scalable applications by facilitating the communication and coordination of various components and modules within a Node.js application.
Example of combined concepts of File System, Modules and EventEmitters
code in the self created module logEvent.js
const { format } = require("date-fns");
const { v4: uuid } = require("uuid");
const fs = require("fs");
const fsPromises = require("fs").promises;
const path = require("path");
const logEvents = async (message) => {
const dateTime = `${format(new Date(), "ddMMyyyy \t HH:mm:ss")}`;
const logItem = `${dateTime}\t${uuid()}\t${message}\n`;
try {
//This will create a file eventLog.txt inside a folder name logs and write the logItem
//first check if this directory exist or not
if (!fs.existsSync(path.join(__dirname, "logs"))) {
//if not exist then make the dir
await fsPromises.mkdir(path.join(__dirname, "logs"));
}
await fsPromises.appendFile(
path.join(__dirname, "logs", "eventLog.txt"),
logItem
);
} catch (err) {
console.log(err);
}
};
module.exports = logEvents;
code in the index.js
const logEvents = require("./logEvents");
//working with Events common-core module
const EventEmitter = require("events");
//This is strange syntax but it is from docs.
class MyEvent extends EventEmitter {}
//initialize the object
const myEvent = new MyEvent();
// so .on listens for the event, here it is listening for log even
myEvent.on("log", (msg) => logEvents(msg));
//simulating a 2 sec delay on event emitter here
setTimeout(() => {
//emit the event log so we use .emit
myEvent.emit("log", "Message : log event emitted");
}, 2000);
In this case the ouput will be a new folder created logs and in this folder there will be a file with name eventlog.txt and in that file there will be the message in each log as follows :
20102023 15:46:12 4acb4dd9-020a-488c-9e3a-6df12630dad3 Message : log event emitted
References to the above source of information are from the YT videos of Dave Gray
Top comments (0)