Sub topic 3
Strings to Bytes and Back
This chapter assumes you know ArrayBuffer, typed array views, and DataView from the earlier chapters, and that you are comfortable with Promises and fetch.
Strings to Bytes and Back
TextEncoder turns a string into UTF-8 bytes in a Uint8Array. TextDecoder turns bytes back into a string. A string's length and its byte length are often different.
const bytes = new TextEncoder().encode('héllo');
console.log(bytes.length); // 6, because 'é' takes two bytes
console.log(new TextDecoder().decode(bytes)); // "héllo"Getting Bytes from fetch, Blob, and File
Response.arrayBuffer() and Blob.arrayBuffer() both resolve to an ArrayBuffer. A File is a Blob, so the same method works on it. To read the bytes, wrap the buffer in a view.
async function loadBytes(url) {
const response = await fetch(url);
return new Uint8Array(await response.arrayBuffer());
}Parsing a Binary Record Format
DataView reads fields of mixed types at any offset, including offsets that are not aligned to the field size.
// Layout: uint8 version, uint16 id (big-endian), float32 value (big-endian)
function parseRecord(buffer) {
const dv = new DataView(buffer);
return { version: dv.getUint8(0), id: dv.getUint16(1), value: dv.getFloat32(3) };
}
const dv = new DataView(new ArrayBuffer(7));
dv.setUint8(0, 1); dv.setUint16(1, 513); dv.setFloat32(3, 2.5);
console.log(parseRecord(dv.buffer)); // { version: 1, id: 513, value: 2.5 }64-Bit Integers with BigInt Typed Arrays
BigInt64Array and BigUint64Array store BigInt values. If you assign a Number to one of their elements, it throws a TypeError.
const big = new BigInt64Array(1);
big[0] = 2n ** 63n - 1n;
console.log(big[0]); // 9223372036854775807nResizable Buffers and transfer
ES2024 lets a buffer grow up to maxByteLength. A view created without a length tracks the buffer's current size. transfer() moves the contents to a new buffer and detaches the old one.
const buf = new ArrayBuffer(4, { maxByteLength: 16 });
const view = new Uint8Array(buf);
buf.resize(12);
console.log(view.length); // 12
const moved = buf.transfer();
console.log(buf.detached, moved.byteLength); // true 12Moving Buffers Between Workers
If you list a buffer in postMessage's transfer list, the buffer moves to the worker without being copied. The sender's buffer is left detached.
const worker = new Worker('worker.js');
const data = new ArrayBuffer(1024);
worker.postMessage(data, [data]);
console.log(data.byteLength); // 0Shared Memory with SharedArrayBuffer and Atomics
Several agents can see a SharedArrayBuffer at the same time. Use Atomics operations on its integer views so that reads and updates do not race.
const counter = new Int32Array(new SharedArrayBuffer(4));
Atomics.add(counter, 0, 1);
console.log(Atomics.load(counter, 0)); // 1Exercise
What does new TextEncoder().encode('€').length return, and why?
Show answer
It returns 3, because '€' (U+20AC) takes three bytes in UTF-8, even though the string's length is 1.
Exercise
You need to send a 50 MB buffer to a worker and you no longer need it on the main thread. Should you transfer it, or use a SharedArrayBuffer?
Show answer
Transfer it with postMessage(buf, [buf]). It moves without copying and does not need shared memory or cross-origin isolation.