Comparison of JavaScript binary data objects

There are a set of objects for dealing with binary data in JavaScript, which are slightly different on NodeJS and in the browser.
Common to NodeJS and browser: ArrayBuffer
There is an `ArrayBuffer` object, which is the underlying binary data storage for a set of other array types:
- DataView: This provides a way to read and write arbitrary data from an ArrayBuffer.
- Uint8Array: This allows access to individual bytes, as unsigned values from 0 to 255
- Int8Array: This allows access to individual bytes, as signed values from -128 to 127
- Uint16Array: This allows access to individual 16-bit elements, as unsigned values from 0 to 65,535
- Int16Array: This allows access to individual 16-bit elements, as signed values from -32,768 to 32,767
- Uint32Array: This allows access to individual 32-bit elements, as unsigned values from 0 to 4,294,967,295
- Int32Array: This allows access to individual 32-bit elements, as signed values from -2,147,483,648 to 2,147,483,647
- Float32Array: This allows access to individual 32-bit elements, as floating-point values in IEEE 754 format
- Float64Array: This allows access to individual 64-bit elements, as floating-point values in IEEE 754 format
- SharedArrayBuffer: A type of ArrayBuffer that can be shared between multiple threads or processes
These objects are created from an ArrayBuffer like this:
const myArrayBuffer = new ArrayBuffer(10) // 10 bytes
const bytes = new Uint16Array( myArrayBuffer )
Objects only available in NodeJS
There is something to be very careful of with Buffer which will surprise you if you are not aware of it, and that is that your data might not be the only thing in the Buffer, and might not be at the start.
// TODO: Make buffer with some actual data in (eg. simulating loading a file?)
const myBuffer = new Buffer(10)
const myArray = new UInt8Array( myBuffer )
console.log( myArray.toString() ) // Surprise!
This prints out something like this:
xxx
The proper way to fetch the data is to take a slice of the Buffer based on its `byteOffset` and `byteLength` fields:
const myArray = new UInt8Array( myBuffer.slice( myBuffer.byteOffset, myBuffer.byteOffset + myBuffer.byteLength ) )