Skip to content

Commit

Permalink
refactor(remix-node): remove recursion from stream utilities (#7245)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacob-ebey authored Aug 23, 2023
1 parent 8cb33ce commit ebc148c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 28 deletions.
5 changes: 5 additions & 0 deletions .changeset/remove-stream-recursion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@remix-run/node": patch
---

remove recursion from stream utilities
46 changes: 18 additions & 28 deletions packages/remix-node/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,24 @@ export async function writeReadableStreamToWritable(
writable: Writable
) {
let reader = stream.getReader();
let flushable = writable as { flush?: Function };

async function read() {
let { done, value } = await reader.read();

if (done) {
writable.end();
return;
}
try {
while (true) {
let { done, value } = await reader.read();

writable.write(value);
if (done) {
writable.end();
break;
}

// If the stream is flushable, flush it to allow streaming to continue.
let flushable = writable as { flush?: Function };
if (typeof flushable.flush === "function") {
flushable.flush();
writable.write(value);
if (typeof flushable.flush === "function") {
flushable.flush();
}
}

await read();
}

try {
await read();
} catch (error: any) {
writable.destroy(error);
} catch (error: unknown) {
writable.destroy(error as Error);
throw error;
}
}
Expand All @@ -56,20 +50,16 @@ export async function readableStreamToString(
let reader = stream.getReader();
let chunks: Uint8Array[] = [];

async function read() {
while (true) {
let { done, value } = await reader.read();

if (done) {
return;
} else if (value) {
break;
}
if (value) {
chunks.push(value);
}

await read();
}

await read();

return Buffer.concat(chunks).toString(encoding);
}

Expand Down

0 comments on commit ebc148c

Please sign in to comment.