Sub topic 11
Getting Bytes from fetch, Blob, and File
This chapter assumes you know Promises and async/await, basic fetch, and how to wrap an ArrayBuffer in a Uint8Array (covered earlier). Real binary data usually comes from the network or from the user's disk, not from new ArrayBuffer(). This chapter shows the standard ways to turn those sources into bytes you can inspect.
The common model
Every source in this chapter hands you an ArrayBuffer through a Promise. From there you wrap it in a typed array or a DataView, as in earlier chapters.
From fetch
Response.arrayBuffer() reads the whole body and resolves to an ArrayBuffer.
async function loadBytes(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const buffer = await response.arrayBuffer();
return new Uint8Array(buffer);
}You can read a response body only once. After calling arrayBuffer(), a call to text() or json() on the same response rejects with a TypeError. If you need the body twice, call response.clone() before reading.
From Blob
A Blob is an immutable chunk of bytes with an optional MIME type. You can build one from strings, buffers, and typed arrays. Strings are encoded as UTF-8.
async function main() {
const blob = new Blob([new Uint8Array([1, 2, 3]), 'hi'], {
type: 'application/octet-stream',
});
console.log(blob.size); // 5
const bytes = new Uint8Array(await blob.arrayBuffer());
console.log(bytes); // Uint8Array(5) [1, 2, 3, 104, 105]
}
main();blob.slice(start, end) returns a new Blob covering a byte range. It does not read any data until you call arrayBuffer() on the result. That makes it cheap to read only a file's header.
From File
A File is a Blob with a name and a lastModified date. Files typically come from an <input type="file"> element or from drag and drop. This browser example checks whether the chosen file starts with the 8-byte PNG signature:
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async () => {
const file = input.files[0];
if (!file) return;
const header = new Uint8Array(await file.slice(0, 8).arrayBuffer());
const isPng = PNG_SIGNATURE.every((b, i) => header[i] === b);
console.log(file.name, file.size, isPng);
});Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting `await` | You get a Promise instead of bytes | `await` the `arrayBuffer()` call |
| Reading a body twice | `TypeError: body used already` | Read once, or `clone()` first |
| Using `response.text()` on binary data | Corrupted bytes (U+FFFD replacement characters) | Use `arrayBuffer()` |
| Reading a huge file to check a header | High memory use | `slice()` the range first |
| Reaching for `FileReader` | Callback-style code | Prefer `blob.arrayBuffer()` |
FileReader.readAsArrayBuffer still works, but the Promise-based arrayBuffer() method replaces it in modern code.
Exercise
A user selects a 2 GB video file, and you only need its first 12 bytes. Write the expression that gets those bytes as a Uint8Array, and explain why it is better than calling file.arrayBuffer() and then subarray(0, 12).
Show answer
Use new Uint8Array(await file.slice(0, 12).arrayBuffer()). Calling slice on the Blob only describes a byte range, so just 12 bytes are read into memory. Calling file.arrayBuffer() first would load all 2 GB, and subarray would then give you a view into that huge buffer.
Exercise
Code calls await response.arrayBuffer() and later await response.json() on the same Response. What happens, and how do you fix it?
Show answer
The json() call rejects with a TypeError because the body has already been read. Call response.clone() before the first read and read the clone for the second format. If the bytes are UTF-8 JSON, you can also decode them yourself with TextDecoder and JSON.parse.