diff --git a/doc/api/stream.md b/doc/api/stream.md index 7c0cdfe8e5d531..52fc787f287cc2 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -2376,6 +2376,9 @@ changes: underlying stream will _not_ be aborted if the signal is aborted. The callback will get called with an `AbortError`. All registered listeners added by this function will also be removed. + * `autoCleanup` {boolean} remove all registered stream listeners. + **Default:** `true`. + * `callback` {Function} A callback function that takes an optional error argument. * Returns: {Function} A cleanup function which removes all registered diff --git a/lib/internal/streams/end-of-stream.js b/lib/internal/streams/end-of-stream.js index 806280ebc1f1d2..50569bca1c655a 100644 --- a/lib/internal/streams/end-of-stream.js +++ b/lib/internal/streams/end-of-stream.js @@ -19,6 +19,7 @@ const { validateAbortSignal, validateFunction, validateObject, + validateBoolean } = require('internal/validators'); const { Promise } = primordials; @@ -243,8 +244,19 @@ function eos(stream, options, callback) { } function finished(stream, opts) { + let autoCleanup = true; + if (opts === null) { + opts = kEmptyObject; + } + if (opts.autoCleanup) { + validateBoolean(opts.autoCleanup, 'autoCleanup'); + autoCleanup = opts.autoCleanup; + } return new Promise((resolve, reject) => { - eos(stream, opts, (err) => { + const cleanup = eos(stream, opts, (err) => { + if (autoCleanup) { + cleanup(); + } if (err) { reject(err); } else {