ArrayBuffer and How to use it.

Subscribe to my newsletter and never miss my upcoming articles

An ArrayBuffer is an opaque representation of bytes available in memory. It is likened to a Blob which is an opaque representation of data available on a disk.

Its constructor takes a parameter which is the length in bytes like so:

 const myBuffer = new ArrayBuffer(64);

The value of an ArrayBuffer has a read-only property: byteLength - which expresses its length in bytes.

It provides a slice() instance method which creates a new ArrayBuffer from an existing one, taking a begin position and an optional length.

const myBuffer = new ArrayBuffer(64);
const slicedBuffer = myBuffer.slice(32, 8);

Fetching Data from the web as an ArrayBuffer

A blob can be dowloaded from the web and stored into an ArrayBuffer using XHR:

const downloadBlob = (url, cb) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'arraybuffer';
    xhr.onload = () =>  cb(xhr.response);
    xhr.send(null);
 }

That's all guys :)

No Comments Yet