Reading file contents into user supplied array avoids unnecessary copies. For example you can just get a pointer to an area in a WASM memory and directly read the file instead of first reading it into an useless ArrayBuffer and then doing a slow copy:
// file is a File or Blob// wasm is a WebAssembly module instance wrapper with some additional methods like malloc addedconstreader=newFileReader();constptr=wasm.malloc(file.size);constarray=newUint8Array(wasm.memory.buffer,ptr,file.size);try{letbytesRead=awaitreader.readIntoUint8Array(file,array);// Done}catch(e){// Error}It also allows reading files while using minimal memory and allocations:
constreader=newFileReader();constbufferPtr=wasm.malloc(8192);constbuffer=newUint8Array(wasm.memory.buffer,bufferPtr,8192);lettotalBytesRead=0;while(totalBytesRead<file.size){conststart=totalBytesRead;constend=Math.min(start+8192,file.size);constbytesRead=awaitreadIntoUint8Array(file.slice(start,end),buffer);wasm.process(bufferPtr,bytesRead);totalBytesRead+=bytesRead;}Doing the same with current APIs would allocate a ton of small ArrayBuffers...
Reading file contents into user supplied array avoids unnecessary copies. For example you can just get a pointer to an area in a WASM memory and directly read the file instead of first reading it into an useless ArrayBuffer and then doing a slow copy:
It also allows reading files while using minimal memory and allocations:
Doing the same with current APIs would allocate a ton of small ArrayBuffers...