Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stream: fix eventNames() to not return not defined events #51331

Merged
merged 1 commit into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/internal/streams/legacy.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const {
ArrayIsArray,
ObjectSetPrototypeOf,
ReflectOwnKeys,
} = primordials;

const EE = require('events');
Expand Down Expand Up @@ -93,6 +94,16 @@ Stream.prototype.pipe = function(dest, options) {
return dest;
};

Stream.prototype.eventNames = function eventNames() {
const names = [];
for (const key of ReflectOwnKeys(this._events)) {
if (typeof this._events[key] === 'function' || (ArrayIsArray(this._events[key]) && this._events[key].length > 0)) {
names.push(key);
}
}
return names;
};

function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
Expand Down
42 changes: 42 additions & 0 deletions test/parallel/test-stream-event-names.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use strict';

require('../common');
const assert = require('assert');
const { Readable, Writable, Duplex } = require('stream');

{
const stream = new Readable();
assert.strictEqual(stream.eventNames().length, 0);
}

{
const stream = new Readable();
stream.on('foo', () => {});
stream.on('data', () => {});
stream.on('error', () => {});
assert.deepStrictEqual(stream.eventNames(), ['error', 'data', 'foo']);
}

{
const stream = new Writable();
assert.strictEqual(stream.eventNames().length, 0);
}

{
const stream = new Writable();
stream.on('foo', () => {});
stream.on('drain', () => {});
stream.on('prefinish', () => {});
assert.deepStrictEqual(stream.eventNames(), ['prefinish', 'drain', 'foo']);
}
{
const stream = new Duplex();
assert.strictEqual(stream.eventNames().length, 0);
}

{
const stream = new Duplex();
stream.on('foo', () => {});
stream.on('finish', () => {});
assert.deepStrictEqual(stream.eventNames(), ['finish', 'foo']);
}