CKTIS / JavaScript
Blob.stream() and Blob.size: reading bytes versus counting them
Use `blob.size` to get the total byte count without reading the contents, and `blob.stream()` to process those bytes in chunks.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
blob.size // number of bytes; read-only property
blob.stream() // ReadableStream of bytes; no argumentsBlob.stream/size pairs two instance members. blob.size is a read-only property: it gives the total byte count as a Number. Access it without parentheses. It is neither a character count nor a count of bytes read so far. The Blob constructor encodes string parts as UTF-8, so a JavaScript string’s length can differ from the blob’s size.
blob.stream() is an instance method with no arguments. It returns a fresh ReadableStream of raw bytes. Use size when you only need the total and stream() when you want to process chunks without collecting the entire contents in one buffer. Do not assume a fixed chunk size. To read from the beginning again, call blob.stream() again.
getReader() locks the stream to that reader. Await read() and check done before using value: done: true means there is no next chunk. A read can reject, so use releaseLock() in finally. Releasing the lock does not rewind or cancel the stream.
Blob and ReadableStream are web platform APIs, not language features guaranteed by ECMAScript 2024. Check support in your target runtime.
Examples
(async () => {
const blob = new Blob(["A\u00E9"]);
const reader = blob.stream().getReader();
let bytesRead = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
bytesRead += value.byteLength;
}
} finally {
reader.releaseLock();
}
console.log(`size=${blob.size}; bytesRead=${bytesRead}`);
})().catch((error) => console.error(error));Result
size=3; bytesRead=3
In UTF-8, `A` takes one byte and `é` takes two. After a complete read, the sum of `value.byteLength` is 3, matching `blob.size` regardless of the chunk boundaries.
Related lessons
- JavaScript · Lesson 4 · Advanced · Version: 4