Skip to content

Commit

Permalink
Proxy process.on("exit") to avoid MaxListenersExceededWarning
Browse files Browse the repository at this point in the history
This fixes #30, working around node's MaxListenersExceededWarning by creating a "proxy" event emitter to forward `exit` events.

This is a more concise alternative to #34.
  • Loading branch information
mike-marcacci committed Apr 12, 2021
1 parent 0d46a25 commit c52fa68
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import fs from "fs";
import os from "os";
import path from "path";
import { Readable, ReadableOptions, Writable, WritableOptions } from "stream";
import { EventEmitter } from "events";

export class ReadAfterDestroyedError extends Error {}
export class ReadAfterReleasedError extends Error {}
Expand All @@ -12,6 +13,12 @@ export interface ReadStreamOptions {
encoding?: ReadableOptions["encoding"];
}

// Work around node's MaxListenersExceededWarning for highly concurrent
// workloads by creating a "proxy" event emitter. See:
// https://github.com/mike-marcacci/fs-capacitor/issues/30
const processExitProxy = new EventEmitter() as EventEmitter;
process.addListener("exit", () => processExitProxy.emit("exit"));

export class ReadStream extends Readable {
private _pos: number = 0;
private _writeStream: WriteStream;
Expand Down Expand Up @@ -117,7 +124,7 @@ export class WriteStream extends Writable {
}

// Cleanup when the process exits or is killed.
process.addListener("exit", this._cleanupSync);
processExitProxy.addListener("exit", this._cleanupSync);

this._fd = fd;
this.emit("ready");
Expand All @@ -126,7 +133,7 @@ export class WriteStream extends Writable {
}

_cleanupSync = (): void => {
process.removeListener("exit", this._cleanupSync);
processExitProxy.removeListener("exit", this._cleanupSync);

if (typeof this._fd === "number")
try {
Expand Down Expand Up @@ -208,7 +215,7 @@ export class WriteStream extends Writable {

// We avoid removing this until now in case an exit occurs while
// asyncronously cleaning up.
process.removeListener("exit", this._cleanupSync);
processExitProxy.removeListener("exit", this._cleanupSync);
callback(unlinkError || closeError || error);
});
});
Expand Down

0 comments on commit c52fa68

Please sign in to comment.