In depth explanation of various binary object relations in JavaScript

  • 2021-11-14 04:38:22
  • OfStack

The relationship between various objects in the preface of the directory
ArrayBuffer
TypedArray
Uint8ClampedArray
Mutual conversion of characters
DataView
Blob
URL
Summary of data related to FileFileListFileReader for data reading

Preface

Modern JavaScript has to face more complex scenarios, and there are more data transmissions for various types, including binary transmission. In order to facilitate data processing and improve efficiency, ArrayBuffer objects were created.

However, in use, we will find that there are not only ArrayBuffer, but also TypedArray, DataView, Blob, FileReader and other series of objects, which makes people wonder what is the relationship between them. Why are there so many objects? I inquired about the information with questions and tried to sort out the relationship among them.

Relationships between various objects

ArrayBuffer

ArrayBuffer is the most basic JavaScript binary processing object, describing a continuous memory space, its unit is bytes (byte).


const buffer = new ArrayBuffer(32);

This creates a block of 32-byte memory, the length of which can be viewed using buffer. byteLength.

The ArrayBuffer object can do few operations and is not editable. If you need to edit data, use the other two objects TypedArray and

DataView.

TypedArray

TypedArray typed array, TypedArray itself does not store any data, but is specially used to view ArrayBuffer data, so it is called, TypedArray is not a constructor name, but a group of constructors.

Int8Array: 1-bit, 8-bit signed integer Uint8Array: 1-bit, 8-bit unsigned integer Uint8ClampedArray: 1-bit, 8-bit unsigned integer Int16Array: 2-bit, 16-bit unsigned integer Uint16Array: 2-bit, 16-bit unsigned integer Int32Array: 4-bit, 32-bit unsigned integer Uint32Array: 4-bit, 32-bit unsigned integer Float32Array: 4-bit, 32-bit floating-point number without IEEE Float64Array: 8-bit, 64-bit floating-point number without IEEE BigInt64Array: 8-bit, 64 is a binary signed integer BigUint64Array: 8-bit, 64-bit unsigned integer

When creating, you can pass in the length, typedArray, ArrayBuffer and array. Of course, you can also pass in nothing.


const uint1 = new Uint8Array(8);
const uint2 = new Uint16Array(new Uint8Array(8));
const uint3 = new Uint8Array(new ArrayBuffer(8));
const uint4 = new Uint8Array([1, 2, 3]);
const uint5 = new Uint8Array();

In the above typedArray, except that the ArrayBuffer passed in at the time of creation will not create a new ArrayBuffer, other new ArrayBuffer will be created at the bottom during the new process. You can use arr. buffer to access the ArrayBuffer it refers to.

Operationally, ordinary array operations can be used in TypedArray. But because ArrayBuffer describes contiguous memory intervals, we can't delete a certain value, we can only allocate it to 0, and we can't use concat method.

Uint8ClampedArray

Uint8ClampedArray is relatively special at 1 point, which is handled differently in the case of positive and negative overflow.

Others keep only the rightmost (lower) portion of incoming out-of-bounds data and discard overflow data, while Uint8ClampedArray saves 255 for out-of-bounds data and 0 for incoming negative numbers.

Mutual conversion of characters

TypedArray does not pay to transfer string directly, so it needs to transcode 1.

String → Unit8Array


 const string = "Hello";
Uint8Array.from(string.split(""), (e) => e.charCodeAt(0));

Unit8Array → String


 //  Use TextDecoder Object 
const u8 = Uint8Array.of(72, 101, 108, 108, 111);
new TextDecoder().decode(u8);
//  Use fromCharCode Conversion 
const u8 = Uint8Array.of(72, 101, 108, 108, 111);
Array.from(u8, (e) => String.fromCharCode(e)).join("");

DataView

Except for uint2 variable, all the above data are single 1 data types, and uint2 object, which is a 1-segment memory, stores two types of data, which is called composite view. The data type in JavaScript is often not so simple. It is more troublesome to operate with TypedArray only, so there is an DataView object. DataView has more operation methods than TypedArray.


const buffer = new ArrayBuffer(8);
const dataView = new DataView(buffer);

getInt8, getUint8, getInt16, getUint16, getInt32, getUint32, getFloat32, getFloat64 methods are provided.

There are two parameters, the first bit is the section order position, and the second bit is the byte order, which is not required. The return value is byte data at the corresponding position.


const d1 = dataView.getUint8(1);
const d2 = dataView.getUint8(1, true);

Byte position is easy to understand, and byte order can be read "Understanding Byte Order", which is generally:

Large-end byte order (big endian): High-order bytes come first and low-order bytes come later, which is the method for human beings to read and write values. Small-end byte order (little endian): The low-order bytes are in front and the high-order bytes are in the back, that is, they are stored in the form of 0x1122.

By default, large-end byte order is used, and if you want to use small-end byte order, you need to pass in true.

In this way, we have a basic binary read-write scheme. However, there are often more complex data in practical application scenarios, so Blob, FileReader and other objects are derived for special scenarios.

Blob

Blob is the abbreviation of Binary Large Object (binary large object).

The difference with ArrayBuffer is that ArrayBuffer is pure binary data, while Blob is binary data with MIME type. Blob objects can be generated from String, ArrayBuffer, TypedArray, DataView and Blob conveniently.


const blob1 = new Blob(["hello"], { type: "text/plain" });
const blob2 = new Blob([new Uint8Array([72, 101, 108, 108, 111]), " ", "world"], { type: "text/plain" });

Attributes:

size: Read the byte size of the object. type: Read write MIME type

Methods:

slice: Blob fragment was extracted.

URL

During the development, we obtained the binary data of pictures, which can be converted into base64 and written into src, but if the amount of data is very large, or video data, it will exceed its allowable length. We can use URL. createObjectURL to easily create an URL for 1 resource.


const url = URL.createObjectURL(blob1);

A resource URL similar to blob: https://example.com/a6728d20-2e78-4497-9d6c-0ed61b93f11e is generated, which can be directly written into src for use.

When not in use, use URL. revokeObjectURL (url) to destroy its reference and free up its footprint.

Data reading

If we want to look at the data, there are two ways.

First, using an Response object, you can read either string data or arrayBuffer data directly.


const responseText = await new Response(blob2).text();
const responseBuf = await new Response(blob2).arrayBuffer();

Second, use the FileReader object.


const reader = new FileReader();
reader.onload = function (e) {
    console.log(reader.result);
};
reader.readAsText(blob2);

File

File inherits from Blob and adds file-related attribute information.

name: Filename lastModified: Timestamp of last modified time lastModifiedDate: Date Object for Last Modified Time webkitRelativePath: The path to the file. This property is set when selecting a directory in input, which is a non-standard feature.

FileList

An FileList object is a collection of File objects. 1 appears in:

< input type="file" > Control, where the files property is an FileList The DataTransfer object generated in the drag event, where the files property will be 1 FileList

Attributes:

length: You can get how many File the current FileList contains

Methods:

item (index): File data at the specified index position can be obtained, and FileList [index] is directly used instead in general.

FileReader

FileReader mentioned in the section on Blob1. In fact, FileReader objects are specially used to read Blob objects, including extended File objects.

Attributes:

result: The contents of the file. readyState: Status. 0: Not loaded; 1: Loading; 2: Load complete. error: Error message when loading data.

Events:

onload: Triggered after successful loading. onerror: Triggered when a load error occurs. onabort: Triggered on load interrupt. onloadend: Triggered after loading. onloadstart: Triggered when loading begins. onprogress: Triggered during loading.

Methods:

readAsText (blob, "utf-8"): Returns data as text, and the second parameter sets the text encoding. readAsDataURL (blob): Returns data as Data URL. readAsArrayBuffer (blob): Returns data as ArrayBuffer. abort: Abort the operation.

As in the above example, the data is returned as text:


const uint1 = new Uint8Array(8);
const uint2 = new Uint16Array(new Uint8Array(8));
const uint3 = new Uint8Array(new ArrayBuffer(8));
const uint4 = new Uint8Array([1, 2, 3]);
const uint5 = new Uint8Array();
0

Relevant information

MDN related keywords Modern JavaScript tutorial-part 3 binary data, files Ruan 1feng JavaScript tutorial browser model related chapters

Summarize


Related articles: