Can someone explain the rational reading from a Web API (WHATWG) ReadableStream, using the BYOB (Bring Your Own Buffer) reader (ReadableStreamBYOBReader
), why you cannot reuse your own buffer you brought.
Question: What is the point Bringing Your Own Buffer, if the Buffer you brought cannot be reused? What is the remaining advantage of bringing you own buffer? Why not just give the maximum read size?
If I may compare it to a supermarket, where you are encouraged to bring your own shopping bag. The first time you enter the supermarket with you own bag, everything works as expected, the supermarket fills your bag, you empty it at home, wife happy with you, great. Next you try again with your own bag. But supermarket does allow you to fill your bag as it already has been used before. Good luck with explaining this one at home.
The following code demonstrate multiple reads using the same buffer, and as expected fails, after the first attempt. Does not work in Safari, as Safari lacks BYOB support in the first place.
const url = '/01%20-%20Diablo%20Swing%20Orchestra%20-%20Heroines.mp3';
async function byobReader(reader) {
const myBuffer = new Uint8Array(256);
let result;
let i=0;
do {
console.log(`Read iteration ${++i}...`);
result = await reader.read(myBuffer);
console.log(`Read read=${result.value.length} bytes, done=${result.done}`);
} while(!result.done);
}
async function run() {
console.log('fetching...');
const response = await fetch(url);
if (response.ok) {
console.log('HTTP response succussful');
const stream = response.body;
try {
const reader = stream.getReader({mode:'byob'});
console.log('BYOB Reader supported');
await byobReader(reader);
} catch(error) {
console.error(`Failed to initialize BYOB-Reader=${error.message}`);
}
} else {
console.error(`Failed with HTTP-status=${response.status}`);
}
}
run().catch(error => {
console.error(`Error: ${error.message}`);
});