Reputation: 14664
I am interested on reading from file to my own buffer, in order to avoid an additional copy.
There seems to be an experimental technology ReadableStreamBYOBReader. I tested in MS edge that is expected to support accordingly to Browser compatibility table, as well as caniuse.
Here is the snippet that I expected to run in a browser supporting the feature, can you spot an error or explain why it is not working?
console.log(navigator.userAgent)
document.querySelector('#input-file').addEventListener('change', async (e) => {
if(e.target.files[0]){
try{
// Compare two methods of reading a file
const file = e.target.files[0];
const stream = file.stream();
const slice = await file.slice(0, Math.min(file.size, 16)).arrayBuffer()
const my_own_array = new Uint8Array(Math.min(file.size, 16));
// Here is where it fails in my browser
const reader = stream.getReader({mode:'byob'})
console.log(await reader.read(my_own_array));
slice_array = new Int8Array(slice);
// I expect both arrays to have the same data since I read the same file
console.log({allEqual: slice_array.every((v, i) => v === my_wn_array[i])})
console.log(my_own_buffer);
}catch(e){
console.log(e.toString())
}
}
})
Select a file and the script will attempt to load it
<input type=file id=input-file>
What I see here is
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38`
TypeError: Failed to execute 'getReader' on 'ReadableStream': Cannot use a BYOB reader with a non-byte stream
If it works in your browser, please, let me know in the comments.
EDIT: As noted by Xeelley
I should have passed {mode:'byob'}
instead of 'byob'
.
Upvotes: 0
Views: 1137
Reputation: 1136
Check MDN ReadableStream.getReader() Docs.
getReader
accept 1 optional parameter with type object
. So if you need BYOB reader, you should pass reader config like this:
file.stream().getReader({ mode: 'byob' })
Upvotes: 0