diff --git a/doc/api/events.markdown b/doc/api/events.markdown index 797b969ecc..a1dd8a4fbd 100644 --- a/doc/api/events.markdown +++ b/doc/api/events.markdown @@ -295,6 +295,24 @@ they were registered, passing the supplied arguments to each. Returns `true` if event had listeners, `false` otherwise. +### emitter.eventNames() + +Returns an array listing the events for which the emitter has registered +listeners. The values in the array will be strings or Symbols. + +```js +const EventEmitter = require('events'); +const myEE = new EventEmitter(); +myEE.on('foo', () => {}); +myEE.on('bar', () => {}); + +const sym = Symbol('symbol'); +myEE.on(sym, () => {}); + +console.log(myErr.eventNames()); + // Prints ['foo', 'bar', Symbol('symbol')] +``` + ### emitter.getMaxListeners() Returns the current max listener value for the `EventEmitter` which is either diff --git a/lib/events.js b/lib/events.js index 5860254654..7103ec393f 100644 --- a/lib/events.js +++ b/lib/events.js @@ -436,6 +436,15 @@ function listenerCount(type) { return 0; } +EventEmitter.prototype.eventNames = function eventNames() { + if (this._eventsCount > 0) { + const events = this._events; + return Object.keys(events).concat( + Object.getOwnPropertySymbols(events)); + } + return []; +}; + // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) diff --git a/test/parallel/test-events-list.js b/test/parallel/test-events-list.js new file mode 100644 index 0000000000..4e589b07f2 --- /dev/null +++ b/test/parallel/test-events-list.js @@ -0,0 +1,19 @@ +'use strict'; + +require('../common'); +const EventEmitter = require('events'); +const assert = require('assert'); + +const EE = new EventEmitter(); +const m = () => {}; +EE.on('foo', () => {}); +assert.deepStrictEqual(['foo'], EE.eventNames()); +EE.on('bar', m); +assert.deepStrictEqual(['foo', 'bar'], EE.eventNames()); +EE.removeListener('bar', m); +assert.deepStrictEqual(['foo'], EE.eventNames()); +const s = Symbol('s'); +EE.on(s, m); +assert.deepStrictEqual(['foo', s], EE.eventNames()); +EE.removeListener(s, m); +assert.deepStrictEqual(['foo'], EE.eventNames());