In-depth explanation of various binary object relationships in JavaScript

In-depth explanation of various binary object relationships in JavaScript

Preface

Modern JavaScript has to face more complex scenarios, and there are more types of data transmission, including binary transmission. In order to facilitate data processing and improve efficiency, the ArrayBuffer object was created.

However, when using it, you will find that there are not only ArrayBuffer, but also a series of objects such as TypedArray, DataView, Blob, FileReader, etc., which makes people confused about the relationship between them? Why are there so many objects? I searched for information with these questions in mind and tried to sort out the relationships.

Relationships between various objects

ArrayBuffer

ArrayBuffer is the most basic binary object in JavaScript, which describes a continuous memory space in bytes.

const buffer = new ArrayBuffer(32);

In this way, we have created a 32-byte memory area, and we can use buffer.byteLength to check its length.

ArrayBuffer objects can do very little and are not editable. If you need to edit data, you need to use two other objects, TypedArray and

DataView.

TypedArray

TypedArray is a typed array. TypedArray itself does not store any data, but is specifically used to view ArrayBuffer data. That is why it is called TypedArray. It is not the name of a specific constructor, but a general name for 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 bits, 16-bit unsigned integer
  • Uint16Array: 2 bits, 16-bit unsigned integer
  • Int32Array: 4-bit, 32-bit unsigned integer
  • Uint32Array: 4-bit, 32-bit unsigned integer
  • Float32Array: 4 bits, 32-bit non-IEEE floating point
  • Float64Array: 8-bit, 64-bit IEEE floating point
  • BigInt64Array: 8-bit, 64-bit binary signed integer
  • BigUint64Array: 8-bit, 64-bit unsigned integer

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

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 for the ArrayBuffer passed in during creation, a new ArrayBuffer will be created at the bottom layer during the new process. You can use arr.buffer to access the ArrayBuffer it refers to.

All operations on ordinary arrays can be used in TypedArray. But because ArrayBuffer describes a continuous memory range, we cannot delete a value and can only assign it to 0. There is no way to use the concat method.

Uint8ClampedArray

Uint8ClampedArray is a bit special, and handles positive and negative overflows differently.

For other out-of-bounds data, only the rightmost (lowest bit) portion is retained and the overflow data is discarded. However, Uint8ClampedArray saves out-of-bounds data as 255 and negative numbers as 0.

Conversion between characters

TypedArray does not pass strings directly, so they need to be transcoded first.

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);
// Convert using fromCharCode const u8 = Uint8Array.of(72, 101, 108, 108, 111);
Array.from(u8, (e) => String.fromCharCode(e)).join("");

DataView

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

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

Provides getInt8, getUint8, getInt16, getUint16, getInt32, getUint32, getFloat32, getFloat64 methods.

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

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

The byte position is easy to understand, and the byte order can be read in "Understanding Byte Order". In general, it is:

  • Big endian: The high-order byte comes first, and the low-order byte comes last. This is how humans read and write numbers.
  • Little endian: The low-order byte comes first and the high-order byte comes last, that is, it is stored in the form of 0x1122.

By default, big endian byte order is used. If you want to use little endian byte order, you need to pass true.

In this way, we have a basic binary reading and writing solution. However, actual application scenarios often involve more complex data, so objects such as Blob and FileReader are derived for specific scenarios.

Blob

Blob is the abbreviation of Binary Large Object.

The difference between ArrayBuffer and Blob is that ArrayBuffer is pure binary data, while Blob is binary data with MIME type. And it is easy to generate Blob objects from String, ArrayBuffer, TypedArray, DataView, and Blob.

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

property:

  • size: The size in bytes of the object to be read.
  • type: MIME type to read and write

method:

  • slice: Extract a Blob segment.

URL

During development, we get binary data of the image, which we can convert into base64 and write into src, but if the amount of data is large, or video data, it will exceed the allowed length. We can use URL.createObjectURL to easily create a resource URL.

const url = URL.createObjectURL(blob1);

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

Use URL.revokeObjectURL(url) to destroy its reference and release its memory usage when not in use.

Data reading

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

The first method uses the Response object to directly read string data or arrayBuffer data.

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

The second method uses 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: file name
  • lastModified: The timestamp of the last modification time
  • lastModifiedDate: Date object of the last modified time
  • webkitRelativePath: The path to the file. This property is set when a directory is selected in the input. It is a non-standard feature.

FileList

The FileList object is a collection of File objects. Usually appears in:

  • <input type="file"> control, where the files attribute is a FileList
  • The DataTransfer object generated in the drag event, where the files property will be a FileList

property:

  • length: You can get the number of files in the current FileList.

method:

  • item(index): can be used to obtain the File data at the specified index position. In general, FileList[index] is used directly instead.

FileReader

FileReader was mentioned in the Blob section. In fact, the FileReader object is specifically used to read Blob objects, including extended File objects.

property:

  • result: The content of the file.
  • readyState: state. 0: Not loaded; 1: Loading; 2: Loading completed.
  • error: Error message when loading data.

event:

  • onload: Triggered after loading successfully.
  • onerror: Triggered when a loading error occurs.
  • onabort: Triggered when loading is interrupted.
  • onloadend: Triggered after loading is completed.
  • onloadstart: Triggered when loading starts.
  • onprogress: Triggered during loading.

method:

  • readAsText(blob, "utf-8"): Returns data in text form. The second parameter can set the text encoding.
  • readAsDataURL(blob): Returns the data as a Data URL.
  • readAsArrayBuffer(blob): Returns data as an ArrayBuffer.
  • abort: abort the operation.

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

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

Related Materials

  • MDN related keywords
  • Modern JavaScript Tutorial Part 3: Binary Data, Files
  • Ruan Yifeng JavaScript tutorial browser model related chapters

Summarize

This concludes this article about various binary object relationships in JavaScript. For more relevant JS binary object relationship content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

<<:  Detailed explanation of Mencached cache configuration based on Nginx

>>:  MySQL uses mysqldump+binlog to completely restore the deleted database principle analysis

Recommend

How to solve the problem that mysql cannot be closed

Solution to mysql not closing: Right-click on the...

Docker enables multiple port mapping commands

as follows: docker run -d -p 5000:23 -p 5001:22 -...

10 Tips for Mobile App User Interface Design

Tip 1: Stay focused The best mobile apps focus on...

How to use CocosCreator for sound processing in game development

Table of contents 1. Basics of audio playback in ...

Vue practice of preventing multiple clicks

Generally, click events will be divided into diff...

Common scenarios and avoidance methods for index failure in MySQL

Preface I have read many similar articles before,...

Nginx server https configuration method example

Linux: Linux version 3.10.0-123.9.3.el7.x86_64 Ng...

Detailed explanation of the life cycle of Angular components (Part 2)

Table of contents 1. View hook 1. Things to note ...

In-depth analysis of HTML semantics and its related front-end frameworks

About semantics Semantics is the study of the rel...

Sample code for implementing rolling updates of services using Docker Swarm

1. What is Docker Swarm? Docker Swarm is a cluste...

How to visualize sketched charts in Vue.js using RoughViz

introduce A chart is a graphical representation o...

Abbreviation of HTML DOCTYPE

If your DOCTYPE is as follows: Copy code The code ...