Binary Data
ArrayBuffer
new ArrayBuffer(length) - create basic object, which is a reference to the fixed-length contiguous memory area
- e.g. new ArrayBuffer(16) - this allocates a contiguous memory area of 16 bytes and pre-fills it with zeroes
- unlike Array, ArrayBuffer is not dynamic, i.e. it takes exact amount of space in the memory
view - to manipulate an ArrayBuffer a "view" object is needed
- "view" object does not store anything on its own.it gives an interpretation of the bytes stored in the ArrayBuffer
TypedArray
TypedArray - common term for views. they share same properties and methods
- i.e.
- Uint8Array, Uint16Array, Uint32Array - for integer numbers of 8, 16 and 32 bits
- Uint8ClampedArray - for 8-bit integers, but it "clamps" them on assignment
- Int8Array, Int16Array, Int32Array - for signed integer numbers (can be negative)
- Float32Array, Float64Array - for signed floating-point numbers of 32 and 64 bits
- TypedArray has regular Array methods, with some exceptions
TypedArray argument - TypedArray constructor behaves differently depending on passed argument. it can take:
- buffer
- object
- typedArray
- nothing - creates an zero-length typed array
new Uint32Array(buffer) - create a view to treat buffer as a sequence of 32-bit integers
- e.g.
- const buffer = new ArrayBuffer(16)
- const view = new Uint32Array(buffer)
new DataView(buffer) - flexible untyped view over ArrayBuffer
- it uses methods to specify a format, e.g. getUint8(offset)
Variety of TypedArrays
Buffer
Buffer - subclass of Uint8Array, which is used to represent a fixed-length sequence of bytes
- Buffer is used in NodeJS and is present in global scope there
Buffer.from()
toString(encoding?) - get string representation. utf8 is default encoding
Blob
Blob - binary large object. this is a file-like object of immutable binary data
- while ArrayBuffer is a "binary data", a Blob represents "binary data with type"
- Blob can be accessed with object URL or data URL
new Blob(blobParts, options) - create a Blob object via Blob constructor
- blobParts - array of Blob / BufferSource / String
- options - object which contains:
- type - MIME type. by default it's empty string
- endings - defines how the newline characters (\n) should be interpreted if the data is text
URL.createObjectURL(blob) - create URL for on object of type Blob or File to show its content
- blob:<origin>/<uuid> - the format of object URL
- createObjectURL creates unique URLs
- this URL can be used in <a>, <img> or <embed>
URL.revokeObjectURL(url)
Methods
arrayBuffer() - Blob to ArrayBuffer
stream() - returns a ReadableStream, which is a special object that allows to read blob data portion by portion
Binary PDF to Object URL
const pdfBlob = new Blob([data], { type: 'application/pdf' });
return <embed src={URL.createObjectURL(pdfBlob)} type="application/pdf" />;
Image to Object URL
object URL can help displaying image picked from user's computer via <input type="file" />, without upload to server
function handleImageUpload(event) {
const previewImage = event.target.files[0];
// ...
}
return <img src={URL.createObjectURL(previewImage)} />;
File & FileReader
new File(fileParts, fileName, options?) - create File object, which inherits from Blob and is extended with filesystem-related capabilities
- alternatively File object can be received from <input type="file"> or Drag’n’Drop events, e.g. ondragend
new FileReader() - create FileReader object, which is used to read data from Blob or File in one of three formats
- readAsArrayBuffer(blob) - for binary files, to do low-level binary operations
- readAsText(blob, encoding?) - for text files, which should be read as string
- readAsDataURL(blob) - converts Blob to Base64 and returns data URL. data URL can be used as an alternative to object URL
- FileReader delivers the data using events. e.g. onload - is fired when result is ready
Binary PDF to Data URL
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => console.log(reader.result);
Base64
btoa(text) - binary to ascii. is used to encode text string into Base64
- e.g. btoa('Hello, developer')
atob(base64) - ascii to binary. decodes string encoded with Base64
btoa & atob are global functions
Blob to Base64
data URL can be created for future extracting of Base64 string from it:
function blobToBase64(blob) {
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise((resolve) => {
reader.onloadend = () => {
resolve(reader.result.replace('data:application/pdf;base64,', ''));
};
});
}
Decimal to Binary
function decimalToBinary(n) {
const binary = [];
while (n !== 0) {
binary.push(n % 2);
n = Math.floor(n / 2);
}
return binary.reverse().join('');
}