Node.js is an event-driven platform, which means that it uses events to handle asynchronous operations. The built-in events module in Node.js allows you to create and handle custom events in your application.
Here is an example of how to create and handle a custom event in Node.js:
In this example, we first import the events module and create a new class called MyEmitter, which extends the EventEmitter class. Then, we create an instance of the MyEmitter class called myEmitter.
We then use the .on method to attach a listener function to the 'event' event. This listener function will be executed every time the 'event' event is emitted. We then use the .emit method to trigger the 'event' event.
In addition to the .on and .emit methods, the EventEmitter class also provides other methods such as .once which is similar to .on but the listener function will only be executed once and .removeListener() that can be used to remove the listener function from the event.
You can also pass data to the listener function as the second argument to the emit method.
and in the listener function, you can access the data like this
In this way, you can use events in Node.js to handle asynchronous operations and create a more responsive and efficient application.