Javascript文件API读取到缓冲区



我有兴趣从文件读取到我自己的缓冲区,以避免额外的副本。

似乎有一个实验技术ReadableStreamBYOBReader。我在msedge上进行了测试,预计将支持相应的浏览器兼容性表,以及caniuse。

这是我期望在支持该功能的浏览器中运行的代码片段,您能发现错误或解释为什么它不能工作吗?

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>

我看到的是

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

如果它能在你的浏览器中运行,请在评论中告诉我。

EDIT:正如Xeelley所指出的,我应该通过{mode:'byob'}而不是'byob'

查看MDN ReadableStream.getReader() Docs.

getReaderaccept 1可选参数,类型为object。所以如果你需要BYOB阅读器,你应该像这样传递阅读器配置:

file.stream().getReader({ mode: 'byob' })