Skip to content

Commit

Permalink
Add fixed/tested example code to readablestreambyobreader
Browse files Browse the repository at this point in the history
  • Loading branch information
hamishwillee committed Sep 25, 2023
1 parent 1189cce commit 9f81620
Showing 1 changed file with 28 additions and 25 deletions.
53 changes: 28 additions & 25 deletions files/en-us/web/api/readablestreambyobreader/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ As this is a "Bring Your Own Buffer" reader, we also need to create an `ArrayBuf

```js
const reader = stream.getReader({ mode: "byob" });
let buffer = new ArrayBuffer(4000);
let buffer = new ArrayBuffer(200);
```

A function that uses the reader is shown below.
Expand All @@ -62,30 +62,33 @@ function readStream(reader) {
let bytesReceived = 0;
let offset = 0;

while (offset < buffer.byteLength) {
// read() returns a promise that resolves when a value has been received
reader
.read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
.then(function processBytes({ done, value }) {
// Result objects contain two properties:
// done - true if the stream has already given all its data.
// value - some data. Always undefined when done is true.

if (done) {
// There is no more data in the stream
return;
}

buffer = value.buffer;
offset += value.byteLength;
bytesReceived += value.byteLength;

// Read some more, and call this function again
return reader
.read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
.then(processBytes);
});
}
// read() returns a promise that resolves when a value has been received
reader
.read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
.then(function processText({ done, value }) {
// Result objects contain two properties:
// done - true if the stream has already given all its data.
// value - some data. Always undefined when done is true.

if (done) {
logConsumer(`readStream() complete. Total bytes: ${bytesReceived}`);
return;
}

buffer = value.buffer;
offset += value.byteLength;
bytesReceived += value.byteLength;

logConsumer(
`Read ${value.byteLength} (${bytesReceived}) bytes: ${value}`,
);
result += value;

// Read some more, and call this function again
return reader
.read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
.then(processText);
});
}
```

Expand Down

0 comments on commit 9f81620

Please sign in to comment.