From 62033caa4831a3128e56a75a873bdcc91d1903e0 Mon Sep 17 00:00:00 2001 From: Daniel Huigens Date: Mon, 26 May 2025 15:47:54 +0200 Subject: [PATCH] Add `consumeToEnd` convenience function Similar to `readToEnd`, but discard the data. --- lib/index.d.ts | 2 ++ lib/reader.js | 12 ++++++++++++ lib/streams.js | 15 +++++++++++++++ lib/writer.js | 4 ++++ 4 files changed, 33 insertions(+) diff --git a/lib/index.d.ts b/lib/index.d.ts index d13110e..967d61c 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -13,6 +13,8 @@ export function readToEnd any = join?: JoinFn ): Promise>; +export function consumeToEnd(input: MaybeStream): Promise; + export function toStream>( input: InputType ): InputType extends T ? Stream : InputType; diff --git a/lib/reader.js b/lib/reader.js index a61ceb5..264f2dc 100644 --- a/lib/reader.js +++ b/lib/reader.js @@ -204,4 +204,16 @@ Reader.prototype.readToEnd = async function(join=streams.concat) { return join(result); }; +/** + * Consume the entire stream and wait until it ends. + * @async + */ +Reader.prototype.consumeToEnd = async function() { + // eslint-disable-next-line no-constant-condition + while (true) { + const { done } = await this.read(); + if (done) break; + } +}; + export { Reader, externalBuffer }; diff --git a/lib/streams.js b/lib/streams.js index 591eee2..2fd4b30 100644 --- a/lib/streams.js +++ b/lib/streams.js @@ -499,6 +499,20 @@ async function readToEnd(input, join=concat) { return input; } +/** + * Consume a stream to the end. Throws if the input stream errors. + * @param {ReadableStream|Uint8array|String} input + * @async + */ +async function consumeToEnd(input) { + if (isArrayStream(input)) { + return input.consumeToEnd(); + } + if (isStream(input)) { + return getReader(input).consumeToEnd(); + } +} + /** * Cancel a stream. * @param {ReadableStream|Uint8array|String} input @@ -576,6 +590,7 @@ export { passiveClone, slice, readToEnd, + consumeToEnd, cancel, fromAsync }; diff --git a/lib/writer.js b/lib/writer.js index 24edd89..d72e94e 100644 --- a/lib/writer.js +++ b/lib/writer.js @@ -40,6 +40,10 @@ ArrayStream.prototype.readToEnd = async function(join) { return result; }; +ArrayStream.prototype.consumeToEnd = async function() { + await this[doneWritingPromise]; +}; + ArrayStream.prototype.clone = function() { const clone = new ArrayStream(); clone[doneWritingPromise] = this[doneWritingPromise].then(() => {