Skip to content

Commit 0c7adfc

Browse files
committed
stream: fix eventNames() to not return not defined events
1 parent 5fb6305 commit 0c7adfc

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

lib/events.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ const {
4949
SymbolFor,
5050
SymbolAsyncIterator,
5151
SymbolDispose,
52+
ArrayIsArray,
5253
} = primordials;
5354
const kRejection = SymbolFor('nodejs.rejection');
5455

@@ -888,7 +889,13 @@ function listenerCount(type, listener) {
888889
* @returns {any[]}
889890
*/
890891
EventEmitter.prototype.eventNames = function eventNames() {
891-
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
892+
const names = [];
893+
for (const key of ReflectOwnKeys(this._events)) {
894+
if (typeof this._events[key] === 'function' || (ArrayIsArray(this._events[key]) && this._events[key].length > 0)) {
895+
names.push(key);
896+
}
897+
}
898+
return names;
892899
};
893900

894901
function arrayClone(arr) {
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
'use strict';
2+
3+
require('../common');
4+
const assert = require('assert');
5+
const { Readable, Writable, Duplex } = require('stream');
6+
7+
{
8+
const stream = new Readable();
9+
assert.strictEqual(stream.eventNames().length, 0);
10+
}
11+
12+
{
13+
const stream = new Readable();
14+
stream.on('foo', () => {});
15+
stream.on('data', () => {});
16+
stream.on('error', () => {});
17+
assert.deepStrictEqual(stream.eventNames(), ['error', 'data', 'foo']);
18+
}
19+
20+
{
21+
const stream = new Writable();
22+
assert.strictEqual(stream.eventNames().length, 0);
23+
}
24+
25+
{
26+
const stream = new Writable();
27+
stream.on('foo', () => {});
28+
stream.on('drain', () => {});
29+
stream.on('prefinish', () => {});
30+
assert.deepStrictEqual(stream.eventNames(), ['prefinish', 'drain', 'foo']);
31+
}
32+
{
33+
const stream = new Duplex();
34+
assert.strictEqual(stream.eventNames().length, 0);
35+
}
36+
37+
{
38+
const stream = new Duplex();
39+
stream.on('foo', () => {});
40+
stream.on('finish', () => {});
41+
assert.deepStrictEqual(stream.eventNames(), ['finish', 'foo']);
42+
}

0 commit comments

Comments
 (0)