EventEmitter: All EventEmitters emit the event ‘newListener‘ when new listeners are added and ‘removeListener‘ when existing listeners are removed. It is defined and exposed by the events module:
To import EventEmitter, use the following import statement:
const EventEmitter = require('events');
NodeEventTarget: The EventTarget and Event objects are a Node.js-specific implementation of the EventTarget Web API that is exposed by some Node.js core APIs.
Difference between EventEmitter and NodeEventTarget:
|Event Emitter||Node Event Target|
|It implements is-a relationship with the events Module.||It implements is-a relationship with the EventTarget API.|
|In eventEmitter, for the same event, we can allow multiple listeners to be registered.||Any listener can be registered once per event type and it gets ignored if attempted to register a listener multiple times.|
|It emulates the most from Events such as ‘error’, ‘Classes’, Emits, etc.||It does not emulate the full EventEmitter APIs like prependListener(), prependOnceListener(), rawListeners(), etc.|
|Its default behavior is to log information and end the current execution.||For ‘error‘ type events, it does not implement any default behavior.|
|If an error occurs within an EventEmitter instance, then the typical action is for an ‘error’ event to be emitted.||It supports EventListener objects and functions as handlers for all event types.|
|All EventEmitter emit the event ‘newListener’, when new listeners are added and ‘removeListener’ when listeners are removed.||It isn’t an instance of EventEmitter and in most cases, it can’t be used in place of an EventEmitter.|
emitter.once( eventName, listener)
nodeEventTarget.once( type, listener[, options])
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.