0

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'.

1 Answer 1

0

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' })
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer, that took one step further, now can you tell why how to construct a byte stream from the file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.