2

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

But in use, you will find that there are not only ArrayBuffer , but also TypedArray , DataView , Blob , FileReader , which makes people confused what is the relationship between them? Why are there so many objects? I checked the information with questions and tried to sort out the relationship.

The relationship between various objects

ArrayBuffer

ArrayBuffer is the most basic JavaScript object that handles binary. It describes a continuous memory space, and its unit is byte ( byte ).

const buffer = new ArrayBuffer(32);

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

ArrayBuffer object can do not many operations, and it 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, it is only used to view ArrayBuffer data, so it is called, TypedArray is not a name of a constructor, but a collective 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-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 bits, 32 bits without IEEE floating point numbers
  • Float64Array : 8 bits, 64 bits without IEEE floating point numbers
  • BigInt64Array : 8 bits, 64 is a binary signed integer
  • BigUint64Array : 8-bit, 64-bit unsigned integer

When you create can be passed length, typedArray , ArrayBuffer , array. Of course, nothing can be passed 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();

Above typedArray , except when you create an incoming ArrayBuffer not newly created ArrayBuffer , in other new bottom creates a new process ArrayBuffer . You can use arr.buffer to access the referenced ArrayBuffer .

Operations on ordinary arrays can be used in TypedArray . But because ArrayBuffer describes a continuous memory range, we cannot delete a certain value. We can only assign it to 0 , and we cannot use the concat method.

Uint8ClampedArray

Uint8ClampedArray relatively special, and the handling is different in the case of positive and negative overflow.

Others only retain the rightmost (low-order) part of the stored out-of-bounds data, discarding the overflow data, and Uint8ClampedArray of-bounds data as 255 , and negative number as 0 .

Character conversion

TypedArray does not directly transfer the string, so you need to transcode it first.

String → Unit8Array

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

Unit8Array → String

// 使用TextDecoder对象
const u8 = Uint8Array.of(72, 101, 108, 108, 111);
new TextDecoder().decode(u8);
// 使用fromCharCode转换
const u8 = Uint8Array.of(72, 101, 108, 108, 111);
Array.from(u8, (e) => String.fromCharCode(e)).join("");

DataView

Except for the uint2 variable, the above data is of a single data type. The uint2 object stores two types of data in a section of memory, which is called compound view. The data types in JavaScript are often not so single. It will be more troublesome to operate TypedArray DataView object. DataView has more various operation methods than TypedArray

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

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

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 the byte data at the corresponding position.

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

to understand, and the byte order can be read 161455c846c6c7 "Understanding Byte Order" , in general:

  • Big endian (big endian): The high-order byte comes first, and the low-order byte comes after. This is the way humans read and write values.
  • Little endian: The low-order byte is first and the high-order byte is last, which is stored in the form of 0x1122.

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

In this way we have a basic binary read and write solution. However, actual application scenarios often have more complex data, so objects such Blob and FileReader

Blob

Blob is the Binary Large Object.

The ArrayBuffer is that ArrayBuffer is pure binary data, while Blob is binary data with the MIME type of And can easily generate Blob objects String , ArrayBuffer , TypedArray , DataView , Blob

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 : The byte size of the read object.
  • type : Read and write the MIME type

method:

  • slice : Extract the Blob fragment.

URL

In the development, we get the binary data of the picture, we can convert it into base64 write it into src , but if the amount of data is large, or the video data, it will exceed its allowable length. We can use URL.createObjectURL to easily create a resource URL.

const url = URL.createObjectURL(blob1);

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

When not in use, use URL.revokeObjectURL(url) destroy its references and release its memory usage.

Data read

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

The first is to use the Response object, you can directly read the string data or arrayBuffer data.

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

The second is to 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 : file name
  • lastModified : Timestamp of the last modification time
  • lastModifiedDate : The Date object last modified
  • webkitRelativePath : The path of the file. When selecting a directory in input, this attribute will be set, non-standard feature .

FileList

FileList object is a collection File Generally appear in:

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

Attributes:

  • length : you can get the current FileList contains how many File

method:

  • item(index) File at the specified index position can be obtained. In general, use FileList[index] directly instead.

FileReader

FileReader mentioned in the section on Blob . In fact, the FileReader object is specifically used to read the Blob object, and of course it also includes the extended File object.

Attributes:

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

event:

  • onload : Triggered after successful loading.
  • onerror : Triggered when loading error.
  • onabort : Triggered when the load is interrupted.
  • onloadend : Triggered after loading.
  • onloadstart : Triggered when loading starts.
  • onprogress : Triggered during loading.

method:

  • readAsText(blob, "utf-8") : Return the data in text form, the second parameter can set the text encoding.
  • readAsDataURL(blob) : Return data in the form of Data URL
  • readAsArrayBuffer(blob) : Return data in the form of ArrayBuffer
  • abort : Abort the operation.

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

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

Relevant information

MDN related keywords

Modern JavaScript Tutorial Three Binary Data, File

Yifeng JavaScript tutorial browser model related chapters


LnEoi
707 声望17 粉丝