Categories
JavaScript Answers

How to inherit from the EventEmitter class with Node.js?

Spread the love

To inherit from the EventEmitter class with Node.js, we use the extends keyword.

For instance, we write

const EventEmitter = require("events");

class MyEmitter extends EventEmitter {
  // ...
}

const myEmitter = new MyEmitter();
myEmitter.on("event", () => {
  console.log("an event occurred!");
});
myEmitter.emit("event");

to create the MyEmitter class that inherits from the EventEmitter class.

We add our own methods inside the class.

Then we create a new instance of MyEmitter with new.

We call on to listen to the 'event' event.

And we call emit to emit the 'event' event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *