Handling Binary Data

1. Understanding Binary Data Types

TypeDescription
ArrayBufferRaw fixed-length byte buffer
TypedArrayTyped view onto buffer
DataViewEndian-aware random access
BlobFile-like immutable byte sequence
SharedArrayBufferCross-thread (needs COOP/COEP)

2. Setting Binary Type

ValueBest For
"arraybuffer"Parsing in JS immediately
"blob"Forwarding to <img>, Response, file save

3. Creating ArrayBuffer

Example: Create + fill

const buf = new ArrayBuffer(16);
const u8 = new Uint8Array(buf);
u8.set([1,2,3,4]);
APIDescription
new ArrayBuffer(n)Allocate n bytes
buf.byteLengthSize
buf.slice(s,e)Copy subrange
buf.transfer() NEWZero-copy ownership transfer

4. Using Typed Arrays

ViewRange
Int8Array-128..127
Uint8Array0..255
Uint8ClampedArray0..255 (saturating)
Int16/Uint16±32K / 0..65K
Int32/Uint32±2.1B / 0..4.2B
Float32/Float64IEEE 754
BigInt64/BigUint6464-bit ints

5. Using DataView

Example: Endian control

const v = new DataView(buf);
v.setUint32(0, 0xCAFEBABE, false);   // big-endian
const n = v.getUint32(0, false);
const f = v.getFloat32(4, true);     // little-endian
MethodDetail
getUint8/16/32Unsigned int read
setInt*Signed int write
getFloat32/64IEEE 754
getBigUint6464-bit

6. Sending Binary Data

SourceSent As
ArrayBufferBinary frame
Uint8ArrayBinary frame
BlobBinary frame (streamed)

7. Receiving Binary Data

Example: Decode incoming

ws.binaryType = "arraybuffer";
ws.onmessage = (e) => {
  const view = new DataView(e.data);
  const opcode = view.getUint8(0);
  dispatch(opcode, view);
};
StepAction
1Set binaryType
2Branch on typeof e.data
3Wrap in DataView / TypedArray

8. Converting Blob to ArrayBuffer

MethodReturns
blob.arrayBuffer()Promise<ArrayBuffer>
blob.bytes() NEWPromise<Uint8Array>
new Response(blob).arrayBuffer()Same result
FileReader.readAsArrayBuffer LEGACYPre-async alternative

9. Implementing Binary Protocol

Example: TLV (type-length-value)

// frame: [u8 type][u16 len][len bytes value]
function frame(type, value) {
  const out = new Uint8Array(3 + value.length);
  out[0] = type;
  new DataView(out.buffer).setUint16(1, value.length, false);
  out.set(value, 3);
  return out.buffer;
}
ElementWidth
Magic2-4 bytes
Version1 byte
Opcode1 byte
Length2/4 bytes
Payloadvariable

10. Handling Large Binary Files

ApproachDetail
ChunkingSplit into N-byte frames with seq
StreamingUse WebSocketStream where supported
HybridHTTP upload + WS notify URL
ResumableSend offset markers, support range
Warning: Browsers may impose memory caps; transferring multi-GB blobs through WS without streaming will OOM tabs.