Skip to content

Commit fa6f928

Browse files
committed
Fix emitting events twice on duplex streams
1 parent 3f202c6 commit fa6f928

3 files changed

Lines changed: 24 additions & 5 deletions

File tree

packages/protocol/src/browser/modules/stream.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ export class Duplex<T extends DuplexProxy = DuplexProxy> extends Writable<T> imp
161161

162162
public constructor(proxyPromise: Promise<T> | T) {
163163
super(proxyPromise);
164-
this._readable = new Readable(proxyPromise);
164+
this._readable = new Readable(proxyPromise, false);
165165
}
166166

167167
public get readable(): boolean {

packages/protocol/src/common/proxy.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,18 @@ const unpromisify = <T extends ServerProxy>(proxyPromise: Promise<T>): T => {
3131
export abstract class ClientProxy<T extends ServerProxy> extends EventEmitter {
3232
protected readonly proxy: T;
3333

34-
public constructor(proxyPromise: Promise<T> | T) {
34+
/**
35+
* You can specify not to bind events in order to avoid emitting twice for
36+
* duplex streams.
37+
*/
38+
public constructor(proxyPromise: Promise<T> | T, bindEvents: boolean = true) {
3539
super();
3640
this.proxy = isPromise(proxyPromise) ? unpromisify(proxyPromise) : proxyPromise;
37-
this.proxy.onEvent((event, ...args): void => {
38-
this.emit(event, ...args);
39-
});
41+
if (bindEvents) {
42+
this.proxy.onEvent((event, ...args): void => {
43+
this.emit(event, ...args);
44+
});
45+
}
4046
}
4147
}
4248

packages/protocol/test/net.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,19 @@ describe("net", () => {
2525
server.close();
2626
});
2727

28+
it("should fail to connect", async () => {
29+
const socket = new net.Socket();
30+
31+
const fn = jest.fn();
32+
socket.on("error", fn);
33+
34+
socket.connect("/tmp/t/e/s/t/d/o/e/s/n/o/t/e/x/i/s/t");
35+
36+
await new Promise((r): nativeNet.Socket => socket.on("close", r));
37+
38+
expect(fn).toHaveBeenCalledTimes(1);
39+
});
40+
2841
it("should connect", async () => {
2942
await new Promise((resolve): void => {
3043
const socket = net.createConnection(socketPath, () => {

0 commit comments

Comments
 (0)