Sub topic 11
Getting Bytes from fetch, Blob, and File
This chapter assumes you can use async/await and fetch, and that you know the earlier material: an ArrayBuffer holds raw bytes, and a typed array or DataView reads them. So far every buffer in this tutorial was created by hand with new ArrayBuffer(n). Real programs get their bytes from somewhere else, such as a network response, a file the user picked, or a Blob built in memory. This chapter covers how to get those bytes into an ArrayBuffer or Uint8Array, and the mistakes people commonly make on the way.
The Common Shape: Everything Ends in an ArrayBuffer
Browser and Node I/O APIs return binary data in a few standard forms. Most of them give you an ArrayBuffer that you wrap in a view yourself. A few newer ones hand you a Uint8Array directly. After that point, nothing about the data depends on where it came from.
| Source | Method | Result | Notes |
|---|---|---|---|
| `Response` | `arrayBuffer()` | `Promise<ArrayBuffer>` | Reads the whole body into memory |
| `Response` | `bytes()` | `Promise<Uint8Array>` | Newer, same as wrapping `arrayBuffer()` |
| `Response` | `body.getReader()` | `Uint8Array` chunks | Streams, so you can track progress or stop early |
| `Blob` / `File` | `arrayBuffer()` | `Promise<ArrayBuffer>` | `File` inherits it from `Blob` |
| `Blob` / `File` | `slice(start, end)` | `Blob` | Doesn't read anything yet, so it's cheap |
| `Blob` / `File` | `stream()` | `ReadableStream` | Chunks are `Uint8Array` |
| `FileReader` | `readAsArrayBuffer()` | event with `result` | Older callback API |
Bytes from fetch
Response.arrayBuffer() reads the whole body and resolves to an ArrayBuffer. Check response.ok first. A 404 page also has a body, and without the check you would end up parsing HTML error text as if it were your binary format.
async function fetchBytes(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status} for ${url}`);
}
const buffer = await response.arrayBuffer();
return new Uint8Array(buffer);
}Recent browsers and Node also provide response.bytes(), which skips the wrapping step and returns a Uint8Array. If you have to support older runtimes, new Uint8Array(await response.arrayBuffer()) gives the same result.
Streaming a Large Response
arrayBuffer() returns nothing until the last byte has arrived. To show download progress, or to stop after reading a header, read response.body as a stream. Each chunk is a Uint8Array, and chunk sizes depend on the network, so your code must not assume any particular size. To get one contiguous array, collect the chunks and then copy them into a single array with set:
async function readAll(response, onProgress = () => {}) {
const reader = response.body.getReader();
const chunks = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
total += value.length;
onProgress(total);
}
const out = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
out.set(chunk, offset);
offset += chunk.length;
}
return out;
}
// Runnable without a network: Response accepts a Blob as its body.
async function demo() {
const response = new Response(new Blob([new Uint8Array([1, 2, 3, 4, 5])]));
const bytes = await readAll(response, (n) => console.log('received', n));
console.log(bytes); // Uint8Array(5) [1, 2, 3, 4, 5]
}
demo();This copies every byte twice, once into the chunks and once into out. For large downloads where the server sends a Content-Length header, you can allocate out once at that size and copy each chunk into it as it arrives. Don't fully trust the header, though. It can be missing, and with compressed responses it gives the compressed size, not the decoded one. Check every write against the array's length.
Bytes from Blob
A Blob is an immutable chunk of bytes with an optional MIME type. You can build one from strings, typed arrays, ArrayBuffers, DataViews, and other Blobs. Strings are encoded as UTF-8. Typed arrays contribute only the bytes inside their view, not the rest of their buffer.
async function blobDemo() {
const header = new Uint8Array([0xca, 0xfe]);
const blob = new Blob([header, 'hé'], { type: 'application/octet-stream' });
console.log(blob.size); // 5: two bytes, then 'h' (1) and 'é' (2)
const bytes = new Uint8Array(await blob.arrayBuffer());
console.log([...bytes].map((b) => b.toString(16))); // ['ca', 'fe', '68', 'c3', 'a9']
const tail = blob.slice(2); // a new Blob, nothing is read yet
console.log(await tail.text()); // "hé"
}
blobDemo();Building a Blob copies the bytes, so changing header afterwards does not change blob. This also makes Blob a common way to send typed-array data back out of a program, for example to trigger a download with URL.createObjectURL(blob) or to upload it as a fetch body.
Bytes from File
A File is a Blob with a name and a lastModified timestamp. You get File objects from an <input type="file"> element, from drag-and-drop (event.dataTransfer.files), or from the File System Access API. Every Blob method works on a File.
The slice method is useful here. It takes a byte range and returns a new Blob without reading anything, so you can check a file's signature without loading a 2 GB video into memory. The example below checks for the 8-byte PNG signature:
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
async function isPng(file) {
const head = new Uint8Array(await file.slice(0, 8).arrayBuffer());
return head.length === 8 && PNG_SIGNATURE.every((b, i) => head[i] === b);
}
// Browser usage, assuming the page contains a file input element:
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async () => {
for (const file of input.files) {
console.log(file.name, file.size, await isPng(file));
}
});Check head.length before comparing. A file shorter than 8 bytes gives a shorter slice, and reading past the end of a typed array returns undefined instead of throwing. In the code above, a short file would fail the comparison anyway, but parsers that read fields without comparing them would silently get undefined.
The Older FileReader API
Code written before about 2019 usually uses FileReader. It works, but it reports results through events instead of Promises. Prefer blob.arrayBuffer() in new code, and wrap FileReader only when you have to support very old environments:
function readWithFileReader(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result); // an ArrayBuffer
reader.onerror = () => reject(reader.error);
reader.readAsArrayBuffer(blob);
});
}Node: Buffer Is a Uint8Array, With a Catch
In Node, fs.readFile and many other APIs return a Buffer. Buffer is a subclass of Uint8Array, so indexing, subarray, and passing it to TextDecoder all work. The catch is that small Buffers are often cut from a shared 8 KB pool. Their .buffer property is the whole pool, and their byteOffset is often not zero.
const b = Buffer.from('hi');
console.log(b instanceof Uint8Array); // true
console.log(b.length); // 2
console.log(b.buffer.byteLength); // usually 8192: the shared pool
console.log(b.byteOffset); // often not 0
// Wrong: this view covers the entire pool
// const dv = new DataView(b.buffer);
// Right: limit the view to this Buffer's bytes
const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
console.log(dv.getUint8(0)); // 104, the code for 'h'
// If an API needs a standalone ArrayBuffer, copy exactly those bytes
const ab = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
console.log(ab.byteLength); // 2The same rule applies in browsers to any Uint8Array you didn't create yourself, including stream chunks and results of subarray. Whenever you go from a view to its .buffer, pass byteOffset and byteLength along with it.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Your parser reads `<!DO` as a magic number | The server returned an HTML error page | Check `response.ok` before reading |
| `TypeError: body used already` | The body was read twice | Use `response.clone()`, or reuse the buffer |
| Fields contain unrelated data | You built a view on `.buffer` without the offset | Pass `byteOffset` and `byteLength` |
| Fields are `undefined` | The file or slice is shorter than you expected | Check lengths before you read |
| A huge file freezes the tab | `arrayBuffer()` loaded the whole file | Use `slice` or `stream()` instead |
Exercise
You need only the 12-byte header of a 500 MB file a user selected, read through a DataView. Write the line that builds the DataView, and explain why it uses less memory than calling file.arrayBuffer().
Show answer
const dv = new DataView(await file.slice(0, 12).arrayBuffer());. The slice call creates a Blob that refers to the first 12 bytes without reading them. Calling arrayBuffer() on that slice loads only those 12 bytes. Calling file.arrayBuffer() would load all 500 MB into memory.
Exercise
A stream chunk chunk is a Uint8Array with byteOffset 16 and length 4. What is wrong with new DataView(chunk.buffer).getUint32(0), and how do you fix it?
Show answer
The DataView starts at byte 0 of the underlying buffer, which is 16 bytes before the chunk's data. So it reads unrelated bytes. The fix is new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength).getUint32(0).
Exercise
new Blob([new Uint8Array([1, 2]), 'é']).size gives what value, and why?
Show answer
4. The typed array contributes 2 bytes. The string is encoded as UTF-8, and 'é' takes 2 bytes in UTF-8.