Skip to content

Commit

Permalink
use readable event
Browse files Browse the repository at this point in the history
  • Loading branch information
tdraier committed Jan 13, 2025
1 parent 289d880 commit 9aeca0f
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions types/src/shared/utils/streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,25 +43,39 @@ export function readableStreamToReadable(readableStream: ReadableStream) {
const reader = readableStream.getReader();
let reading = false;

return new Readable({
const nodeReadable = new Readable({
async read() {
if (reading) {
console.log("already reading");
return;
}
reading = true;

try {
const { done, value } = await reader.read();
if (done) {
console.log("done");
this.push(null);
} else {
console.log("not done");
reading = !this.push(value); // Pause reading if push() returns false
console.log("set reading=", reading);
}
} catch (error) {
console.log("error", error);
this.destroy(error as Error);
} finally {
reading = false;
}
},
});

nodeReadable.on("readable", () => {
console.log("readable");
reading = false;

if (!reading) {
nodeReadable.read(); // Resume reading when the stream is ready for more data
}
});

return nodeReadable;
}

0 comments on commit 9aeca0f

Please sign in to comment.