CKTIS / JavaScript
DataView: explicit binary format access
DataView reads and writes multibyte values in a buffer with chosen byte order and no alignment requirement.
Version: ECMAScript 2015 onward; resizable ArrayBuffer behavior from ECMAScript 2024; example target: Node.js 24.22.2
Syntax
new DataView(buffer); new DataView(buffer, byteOffset); new DataView(buffer, byteOffset, byteLength)new DataView(buffer, byteOffset?, byteLength?) creates a view over an existing ArrayBuffer or SharedArrayBuffer; it does not copy bytes. Unlike typed arrays, access is not restricted to one element type or aligned offsets. Methods such as getUint16, setFloat32, and getBigInt64 take a byte offset. The optional littleEndian defaults to false, so multibyte values use big-endian order by default.
byteOffset and an explicit byteLength go through ToIndex. A negative result, infinity, or a range beyond the buffer throws RangeError. An access whose full width does not fit in the view also throws RangeError; an invalid receiver, detached buffer, or view made out of bounds by resizing throws TypeError. BigInt methods such as setBigUint64 reject an ordinary Number; pass a value such as 1n.
When byteLength is omitted for a resizable ArrayBuffer, the view tracks the buffer’s current end. An explicit byteLength creates a fixed-length view that can become out of bounds after the buffer shrinks. DataView dates to ECMAScript 2015; resizable ArrayBuffer and length-tracking views are available from ECMAScript 2024.
The scope label DataView.getUint16 denotes the instance method called as view.getUint16(byteOffset, littleEndian?), not a static method of the DataView constructor. It reads exactly 2 bytes at any alignment and returns an integer from 0 through 65535. A littleEndian value of false or undefined selects big-endian and true selects little-endian; a read extending past the view throws RangeError.
Examples
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setUint16(0, 0x1234);
view.setUint16(2, 0x1234, true);
view.setFloat32(4, 1.5, true);
console.log(Array.from(new Uint8Array(buffer)).join(","));
console.log(view.getUint16(0).toString(16), view.getUint16(2, true).toString(16), view.getFloat32(4, true));
console.log(new DataView(buffer, 1, 3).byteOffset);
try { view.getUint32(6); } catch (error) { console.log(error instanceof RangeError); }Result
18,52,52,18,0,0,192,63 1234 1234 1.5 1 true