I'm reading image files with FileReader().readAsArrayBuffer()
and I'm using the md5
library to create a hash of the file. The readAsArrayBuffer()
returns an ArrayBuffer
.
const reader = new FileReader();
reader.onload = (event) => {
// NEED TO CREATE TYPED ARRAY FROM
const binary = new Uint8Array(event.target.result);
const md5Hash = md5(binary);
};
reader.readAsArrayBuffer(imageFile);
From MDN ArrayBuffer
We get that:
The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer.
It is an array of bytes, often refered to in other languages as a "byte array".
You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
Thus, I can't use directly into the md5
function, I need first to acreate on of the type array objects.
My options are:
Which one of the above should I use in my code? And why?
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
There is no general answer to that, that basically depends on the consumer and what format they want to deal with.
For instance, if you wanted to parse the actual file format of a PNG, you'd actually need to be able to read some of its chunks in BigEndian order, meaning you'd need a DataView on most personal computers.
But here your library claims they do support Uint8Array and ArrayBuffer. However, testing it it seems that indeed they fail to handle nude ArrayBuffers, so go with Uint8Array, because that's what your library's docs say.