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 you 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 = 'https://raw.githubusercontent.com/Borewit/test-audio/958e057/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/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}`);
});
If you browser support BYOB, the output will be:
fetching...
HTTP response succussful
BYOB Reader supported
Read iteration 1...
Read read=256 bytes, done=false
Read iteration 2...
Failed to initialize BYOB-Reader=Failed to execute 'read' on 'ReadableStreamBYOBReader': This readable stream reader cannot be used to read as the view has byte length equal to 0
The only clear advantage I can see compared to the ReadableStreamDefaultReader
, is that you can set a constraint on the buffer size.