I don't know why the author did wrap his Uint8Array in a new one... note that I don't really know either the deprecated BlobBuilder API, but one typo I can see in your code is that you need to wrap your TypedArray in a normal Array:
new Blob([new Uint8Array(buffer, byteOffset, length)]);
The Blob() constructor takes a blobParts sequence as first parameter, and then searches for BufferSource, USVStrings and Blob elements in this sequence. So when you pass a TypedArray, it will actually iterate over all the entries of this TypedArray and treat these as USVString (and thus convert their numerical value to UTF-8 strings in the Blob). That's rarely what you want, so better always pass an Array in this constructor.
Note that if you don't need to slice the buffer, it's probably better to directly pass it instead of using an intermediary Uint8Array (but still in a normal Array):
new Blob([buffer]);
Answer from Kaiido on Stack OverflowI don't know why the author did wrap his Uint8Array in a new one... note that I don't really know either the deprecated BlobBuilder API, but one typo I can see in your code is that you need to wrap your TypedArray in a normal Array:
new Blob([new Uint8Array(buffer, byteOffset, length)]);
The Blob() constructor takes a blobParts sequence as first parameter, and then searches for BufferSource, USVStrings and Blob elements in this sequence. So when you pass a TypedArray, it will actually iterate over all the entries of this TypedArray and treat these as USVString (and thus convert their numerical value to UTF-8 strings in the Blob). That's rarely what you want, so better always pass an Array in this constructor.
Note that if you don't need to slice the buffer, it's probably better to directly pass it instead of using an intermediary Uint8Array (but still in a normal Array):
new Blob([buffer]);
var buffer = new ArrayBuffer(32);
new Blob([buffer]);
so the Uint8Array should be
new Blob([new Uint8Array([1, 2, 3, 4]).buffer]);
How to go from Blob to ArrayBuffer
reactjs - How to convert ArrayBuffer to blob so it can be converted to URL for video playback - Stack Overflow
node.js - What is the correct way to send ArrayBuffer or Blob across and reconstruct them? - Stack Overflow
[AskJS] Webworkers: passing blobs faster than passing ArrayBuffers as transferable in Chrome
You can use FileReader to read the Blob as an ArrayBuffer.
Here's a short example:
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);
Here's a longer example:
// ArrayBuffer -> Blob
var uint8Array = new Uint8Array([1, 2, 3]);
var arrayBuffer = uint8Array.buffer;
var blob = new Blob([arrayBuffer]);
// Blob -> ArrayBuffer
var uint8ArrayNew = null;
var arrayBufferNew = null;
var fileReader = new FileReader();
fileReader.onload = function(event) {
arrayBufferNew = event.target.result;
uint8ArrayNew = new Uint8Array(arrayBufferNew);
// warn if read values are not the same as the original values
// arrayEqual from: http://stackoverflow.com/questions/3115982/how-to-check-javascript-array-equals
function arrayEqual(a, b) { return !(a<b || b<a); };
if (arrayBufferNew.byteLength !== arrayBuffer.byteLength) // should be 3
console.warn("ArrayBuffer byteLength does not match");
if (arrayEqual(uint8ArrayNew, uint8Array) !== true) // should be [1,2,3]
console.warn("Uint8Array does not match");
};
fileReader.readAsArrayBuffer(blob);
fileReader.result; // also accessible this way once the blob has been read
This was tested out in the console of Chrome 27—69, Firefox 20—60, and Safari 6—11.
Here's also a live demonstration which you can play with: https://jsfiddle.net/potatosalad/FbaM6/
Update 2018-06-23: Thanks to Klaus Klein for the tip about event.target.result versus this.result
Reference:
- https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsArrayBuffer()
- https://www.w3.org/TR/FileAPI/#dfn-readAsArrayBuffer
The Response API consumes a (immutable) Blob from which the data can be retrieved in several ways. The OP only asked for ArrayBuffer, and here's a demonstration of it.
var blob = GetABlobSomehow();
// NOTE: you will need to wrap this up in a async block first.
/* Use the await keyword to wait for the Promise to resolve */
const arrayBuffer = await new Response(blob).arrayBuffer();
Alternatively you could use this:
new Response(blob).arrayBuffer().then((arrayBuffer) => {
// do something with the arrayBuffer
});
Note: This API isn't compatible with older (ancient) browsers so take a look to the Browser Compatibility Table to be on the safe side ;)
I'm running some tests in Chrome with webworker and I'm finding quite odd that passing blobs back and forth is way, way faster than ArrayBuffers.
This is the testing code I'm using with a 1Gb file:
ArrayBuffer:
const buffer = await fetch('./1GbFile.bin').then(data => data.arrayBuffer());
console.time("Buffer")
worker.onmessage = function(e) {
console.timeEnd("Buffer");
};
worker.onerror = function(e) {
reject(e.message);
};
worker.postMessage(buffer, [buffer]);Blob:
const blob = await fetch('./1GbFile.bin').then(data => data.blob());
console.time("Blob")
worker.onmessage = function(e) {
console.timeEnd("Blob");
};
worker.onerror = function(e) {
reject(e.message);
};
worker.postMessage(blob);And this is the webworker, it just returns the same data it receives:
self.onmessage = function(e) {
const data = e.data;
if (data instanceof ArrayBuffer)
self.postMessage(data, [data]);
else
self.postMessage(data);
}And the staggering results:
Buffer: 34.46484375 ms
Blob: 0.208984375 ms
I knew blob was very optimized in this scenario, but I thought using the transferable option would make it work somehow similar, but it's more than 100 times slower.
And the transferable option is definitely doing its thing, removing the option makes it like 10 times slower.
Edit: The same code is way faster in Firefox:
Buffer: 2ms
Blob: 0ms
Summary
Unless you need the ability to write/edit (using an ArrayBuffer), then Blob format is probably best.
Detail
I came to this question from a different html5rocks page., and I found @Bart van Heukelom's comments to be helpful, so I wanted to elevate them to an answer here.
I also found helpful resources specific to ArrayBuffer and Blob objects. In summary: despite the emphasis on Blob being immutable/"raw data" Blob objects are easy to work with.
Resources that compare / contrast ArrayBuffer vs Blob:
- Mutability
- an
ArrayBuffercan be changed (e.g. with aDataView) - a
Blobis immutable
- an
- Source / Availability in Memory
- Quoting Bart van Heukelom:
- An ArrayBuffer is in the memory, available for manipulation.
- A Blob can be on disk, in cache memory, and other places not readily available
- Access Layer
ArrayBufferwill require some access layer like typed arraysBlobcan be passed directly into other functions likewindow.URL.createObjectURL, as seen in the example from OP's URL.- However, as Mörre points out you may still need
File-related interfaces and API's likeFileReaderto work with a Blob.
- However, as Mörre points out you may still need
- Convert / Generate
- You can generate
BlobfromArrayBufferand vice versa, which addresses the OP's "Aren't both containers comprised of bits?" - ArrayBuffer can be generated from a Blob using the
FileReader'sreadAsArrayBuffermethod , or the async methodconst arrayBuffer = await blob.arrayBuffer()(thanks to @Darren G) - Blob can be generated from an ArrayBuffer as @user3405291 points out
new Blob([new Uint8Array(data)]);, shown in this answer
- You can generate
- Use in Other Libraries
jsZip;(new JSZip()).loadAsync(...)accepts bothArrayBufferandBlob:String/Array of bytes/ArrayBuffer/Uint8Array/Buffer/Blob/Promise
- How does protocol handle ArrayBuffer vs Blob
- Websocket (aka WS / WSS)
- Use the webSocket's
binaryTypeproperty (could have values "arraybuffer" or "blob") to "control the type of binary data being received over the WebSocket connection."
- Use the webSocket's
- XmlHttpRequest (aka XHR)
- Use the xhr's
responseTypeproperty to "to change the expected response type from the server" (valid values include "arraybuffer", "blob", and others like "document", "json", and "text") -
the response property will contain the entity body according to
responseType, as an ArrayBuffer, Blob, Document, JSON, or string.
- Use the xhr's
- Websocket (aka WS / WSS)
Other helpful documentation:
ArrayBuffer
The
ArrayBufferobject is used to represent a generic, fixed-length raw binary data buffer. You cannot directly manipulate the contents of anArrayBuffer; instead, you create one of the typed array objects or aDataViewobject which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
Blob
A
Blobobject represents a file-like object of immutable, raw data.Blobrepresent data that isn't necessarily in a JavaScript-native format. TheFileinterface is based onBlob, inheriting blob functionality and expanding it to support files on the user's system.
It's explained on the page.
ArrayBuffer
An ArrayBuffer is a generic fixed-length container for binary data. They are super handy if you need a generalized buffer of raw data, but the real power behind these guys is that you can create "views" of the underlying data using JavaScript typed arrays. In fact, multiple views can be created from a single ArrayBuffer source. For example, you could create an 8-bit integer array that shares the same ArrayBuffer as an existing 32-bit integer array from the same data. The underlying data remains the same, we just create different representations of it.
BLOB
If you want to work directly with a Blob and/or don't need to manipulate any of the file's bytes, use xhr.responseType='blob':
This is just a demo code snippet and its variations are working perfectly for more than a year until now.
I suspect the recent browser updates for Edge 126.0.2592.87 (Official build) (64-bit) and Chrome 126.0.6478.127 (Official Build) (64-bit) breaks it, because they used the same underlying engine. Firefox seems to be still okay.
var myArray = new Uint8Array(1024 * 1024 * 1024 * 1.8);
var myBlob = new Blob([myArray], {type: "*.*"});
myBlob.slice(0, 10).arrayBuffer();If the code snippet works in the first run then rerun it twice without refreshing browser. You will be greeted with the message "Uncaught DOMException: The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired."
Any thoughts or insights? Appreciated.