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 14, 2021
1 parent 0d46a25 commit 5ac9923
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,4 @@

- Upgrade dependencies.
- **BREAKING:** Drop support for node 13.
- Work around node's MaxListenersExceededWarning (#30 via #42)
14 changes: 11 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,13 @@ 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();
processExitProxy.setMaxListeners(Infinity);
process.addListener("exit", () => processExitProxy.emit("exit"));

export class ReadStream extends Readable {
private _pos: number = 0;
private _writeStream: WriteStream;
Expand Down Expand Up @@ -117,7 +125,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 +134,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 +216,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 5ac9923

Please sign in to comment.