When bytes encode an image or other binary data, a typed array lets you interpret and access them as values of a specified numeric type. Unlike ordinary JavaScript arrays, its elements share a type; a Uint8Array, for example, represents bytes as unsigned 8-bit integers from 0 to 255. Typed arrays provide a way to read and write buffer data, and each has an underlying buffer. section 11.1.2 section 10.1
Listing 11.2 Constructing a buffer using typed arrays
// Create an image header for a PNG file
const chunkLength = new Uint8Array([0, 0, 0, 13]); #A
const chunkType = new TextEncoder().encode("IHDR"); #B
const ihdrData = new Uint8Array(13); #C
ihdrData[8] = 8; #C
ihdrData[9] = 6; #C
const dummyCrc = new Uint8Array(4); #D
const ihdrChunk = new Uint8Array([ #E
...chunkLength, #E
...chunkType, #E
...ihdrData, #E
...dummyCrc, #E
]);
console.assert(
ihdrChunk[16] === 8,
"Bit depth is 8"
);
console.assert(
ihdrChunk[17] === 6,
"Color type 6 means RGBA"
);
const type = String.fromCharCode(
...ihdrChunk.subarray(4, 8)
);
console.assert(type === "IHDR", "Chunk type is IHDR");
This example assembles a PNG header from typed-array chunks, then checks selected byte values and reads the chunk type. section 11.1.2
Node.js Buffer inherits from Uint8Array, so a Buffer can be accessed like an array of bytes. Typed arrays are not ordinary JavaScript arrays: Array.isArray(new Uint8Array()) returns false. Use them when code needs to interpret or construct raw numeric data; their underlying buffer may also be shared with other objects. section 11.1.2
