Blob
Blob represents an immutable chunk of binary data. Its contents aren't held in JS memory; the JS side has only size and type. Call its methods when you need to read the contents.
A Blob comes from one of two places: res.blob() gives downloaded content, and new Blob(parts) creates one from strings or bytes you have.
A Blob can be passed to these APIs: fetch() to send as a request body, UIImage.imageWithData() to create an image, writeBytes() of application.fileSystem to write to a file, and setBytes() of application.keychain to store in the keychain (requires installing @nacrejs/keychain first).
Inheritance: Blob doesn't inherit from any other class.
Constructor
Concatenates strings and bytes into a Blob.
Instance properties
| Property | Description |
|---|---|
size read-only | The number of bytes |
type read-only | The content type, such as 'image/png' |
Instance methods
Both methods can be called any number of times; there's no "read only once" restriction.
| Method | Description |
|---|---|
arrayBuffer() | Gets a copy of the contents as an ArrayBuffer |
text() | Decodes the contents as UTF-8 into a string |
Examples
async function main() {
const blob = new Blob(['前缀-', '后缀'], { type: 'text/plain' });
console.log(blob.size, blob.type);
console.log(await blob.text());
}
main();Result: prints 13 text/plain and 前缀-后缀. size is the number of bytes after UTF-8 encoding; each Chinese character takes 3 bytes.
Differences from the web
- Elements of
partscan't beBlobs;new Blob([blob])throwsTypeError. - There's no
slice(),stream(), orbytes(). There's noFile.
See also
blob()ofResponse: reading downloaded content as aBlobUIImage: turning aBlobinto an image- File system: writing a
Blobto a file