【发布时间】:2021-11-30 21:58:33
【问题描述】:
我有兴趣从文件读取到我自己的缓冲区,以避免额外的副本。
似乎有一种实验技术ReadableStreamBYOBReader。我在 MS edge 中进行了测试,预计将支持Browser compatibility table,以及caniuse。
这是我希望在支持该功能的浏览器中运行的 sn-p,您能发现错误或解释它为什么不工作吗?
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
如果它在您的浏览器中有效,请在 cmets 中告诉我。
编辑:正如Xeelley 所说,我应该通过{mode:'byob'} 而不是'byob'。
【问题讨论】:
标签: javascript cross-browser fileapi