Example 1 — Copy the Header of a File
Reading a file with file.arrayBuffer() or fetch(url).then((r) => r.arrayBuffer()) gives you one big ArrayBuffer. Here the first bytes of a PNG image are typed in by hand so the example runs anywhere; slice() copies the 4-byte signature out.
const fileBytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13]);
const fileBuffer = fileBytes.buffer;
const header = fileBuffer.slice(0, 4);
const headerBytes = new Uint8Array(header);
console.log(header.byteLength); // 4
console.log(JSON.stringify(Array.from(headerBytes))); // [137,80,78,71]
console.log(String.fromCharCode(headerBytes[1], headerBytes[2], headerBytes[3])); // PNG
console.log(fileBuffer.byteLength); // 12 How It Works
- Start from raw file bytes. Every PNG file begins with byte
137followed by the letters P, N, and G.fileBytes.bufferis the underlying 12-byte ArrayBuffer. - Copy the first four bytes.
slice(0, 4)copies indexes 0 to 3 into a new 4-byte buffer; index 4 is the stop position and is not included. - The source keeps its size. Decoding bytes 80, 78, 71 as character codes gives
PNG, andfileBufferstill holds all 12 bytes.

