Node.js emitter.eventNames() Method
Last Updated :
13 Aug, 2020
In Node.js, most of the core APIs are built near around an idiomatic asynchronous and event-driven architecture. EventEmitter class has instances that are emitted as events by all objects, in which these objects expose an eventEmitter.on() function. It is necessary to import events library (require(‘events’)) in order to handle the events.
The emitter.eventNames() (Added in v6.0.0) method is an inbuilt application programming interface of the events module which is used for listing the events for which the emitter has registered listeners and returns it in array form. The type of these listeners are either strings or Symbols.
Syntax:
const EventEmitter = require('events');
emitter.eventNames()
Parameters: This function does not accept any parameters.
Return Value <Array>: It returns an array containing string or Symbol values, listing the events for which the emitter has registered listeners.
Example 1: Filename: index.js
const EventEmitter = require( 'events' );
const newEventEmitter = new EventEmitter();
newEventEmitter.on( 'akash' , () => {});
newEventEmitter.on( 'hadii' , function () {});
console.log(EventEmitter.errorMonitor);
const newSym = Symbol( 'newSymbolofGeekyWorld' );
newEventEmitter.on(newSym, () => {});
console.log(newEventEmitter.eventNames());
|
Output:
Symbol(events.errorMonitor)
[ ‘akash’, ‘hadii’, Symbol(newSymbolofGeekyWorld) ]
Example 2: Filename: index.js
const EventEmitter = require( 'events' );
const newEventEmitter = new EventEmitter();
const someCallback = () => {
console.log( 'Connected to something!' );
};
newEventEmitter.on( 'connectSomething' , someCallback);
newEventEmitter.prependListener( 'alfa' , () => console.log( 'b' ));
newEventEmitter.once( 'geeksforgeeks' ,
() => console.log( 'print in console...' ));
newEventEmitter.prependOnceListener( 'geeksforgeeks' ,
() => console.log( 'geeksforgeeks' ));
newEventEmitter.emit( 'geeksforgeeks' );
const newSym = Symbol( 'newSymbolofGeekyWorld' );
newEventEmitter.on(newSym, () => {});
console.log(newEventEmitter.eventNames());
newEventEmitter.removeListener( 'connectSomething' , someCallback);
console.log(newEventEmitter.eventNames());
|
Run index.js file using the following command:
node index.js
Output:
geeksforgeeks
print in console…
[ ‘connectSomething’, ‘alfa’, Symbol(newSymbolofGeekyWorld) ]
[ ‘alfa’, Symbol(newSymbolofGeekyWorld) ]
Reference: https://nodejs.org/api/events.html#events_emitter_eventnames
Share your thoughts in the comments
Please Login to comment...