This is the fourth day of my participation in the August Text Challenge.More challenges in August

First, basic knowledge

1.1 ArrayBuffer

The ArrayBuffer object is used to represent a generic, fixed-length buffer of raw binary data. An ArrayBuffer does not operate directly, but through a type array object or DataView object, which represents the data in the buffer in specific formats and reads and writes the contents of the buffer in those formats.

An ArrayBuffer is simply a piece of memory, but you can’t use it directly. This is just as if you were in C and malloc was a piece of memory, you would also convert it to unsigned_int32 or int16, whatever array/pointer of the actual type you need to use.

That’s what TypedArray does in JS. All of those Uint32Array and Int16Array provide a “View” to the ArrayBuffer, MDN is called Multiple views on the same data. Subscript reading and writing to them will eventually be reflected on the ArrayBuffer it is built on.

grammar
new ArrayBuffer(length)
Copy the code
  • Parameter: length indicates the size, in bytes, of the ArrayBuffer to be created.
  • Return value: an ArrayBuffer of a specified size whose contents are initialized to 0.
  • Exception: If length is greater thanNumber.MAX_SAFE_INTEGER(>= 2 ** 53) or negative, then one is thrownRangeErrorThe exception.
The sample

The following example creates an 8-byte buffer and references it with an Int32Array:

let buffer = new ArrayBuffer(8);
let view   = new Int32Array(buffer);
Copy the code

As of ECMAScript 2015, ArrayBuffer objects need to be created with the new operator. If the constructor is called without new, TypeError is thrown. For example, executing let ab = ArrayBuffer(10) raises the following exception:

VM109:1 Uncaught TypeError: Constructor ArrayBuffer requires 'new'
    at ArrayBuffer (<anonymous>)
    at <anonymous>:1:10
Copy the code

Some common Web apis, such as FileReader API and Fetch API, also support ArrayBuffer at the bottom. Here we take FileReader API as an example. See how to read a File object as an ArrayBuffer:

const reader = new FileReader();

reader.onload = function(e) {
  let arrayBuffer = reader.result;
}

reader.readAsArrayBuffer(file);
Copy the code

1.2 Unit8Array

Uint8Array array type represents an array of 8-bit unsigned integers that are initialized to 0 when created. Once created, you can refer to the elements of the array as objects or by using an array subscript index.

grammar
new Uint8Array(); // Uint8Array(length); // Create a new Uint8Array(typedArray) with an unsigned integer initialized to 0. new Uint8Array(object); new Uint8Array(buffer [, byteOffset [, length]]);Copy the code
The sample
// new Uint8Array(length); var uint8 = new Uint8Array(2); uint8[0] = 42; console.log(uint8[0]); // 42 console.log(uint8.length); // 2 console.log(uint8.BYTES_PER_ELEMENT); // 1 // new TypedArray(object); Var arr = new Uint8Array([21,31]); console.log(arr[1]); // 31 // new Uint8Array(typedArray); var x = new Uint8Array([21, 31]); var y = new Uint8Array(x); console.log(y[0]); // 21 // new Uint8Array(buffer [, byteOffset [, length]]); var buffer = new ArrayBuffer(8); var z = new Uint8Array(buffer, 1, 4); // new TypedArray(object); // when an object is passed as a parameter, it is like creating a new TypedArray through the typedarray.from () // method. Var iterable = function*(){yield* [1,2,3]; } (); var uint8 = new Uint8Array(iterable); // Uint8Array[1, 2, 3]Copy the code

Read local data in the format of an ArrayBuffer

document.getElementById('f').addEventListener('change', function (e) {
  const file = this.files[0];
  const fileReader = new FileReader();
  fileReader.onload = function () {
    const result = fileReader.result;
    console.log(result)
  }
  fileReader.readAsArrayBuffer(file);
}, false);
Copy the code

Read Ajax request data in the format of an ArrayBuffer

  • Specify the data type of the response with xhr.responseType = “arrayBuffer”
  • Print xhr.response in the onload callback

The front end

const xhr = new XMLHttpRequest();
xhr.open("GET", "ajax", true);
xhr.responseType = "arraybuffer";
xhr.onload = function () {
    console.log(xhr.response)
}
xhr.send();
Copy the code

The Node end

const app = new Koa();
app.use(async (ctx) => {
  if (pathname = '/ajax') {
    ctx.body = 'hello world';
    ctx.status = 200;
  }
}).listen(3000)
Copy the code

Turn ArrayBuffer json

ws.onmessage = function (evt) {
	/ / evt. The data is ArrayBuffer
    // convert it to a uint8 stream
    var uint8_msg = new Uint8Array(evt.data);
    // Decode to a string
    var decodedString = String.fromCharCode.apply(null, uint8_msg);
    console.log(decodedString); 
    // parse to JSON data
    var data = JSON.parse(decodedString);
	console.log(data);
};
Copy the code

Another method, UTF-8, prevents garbled characters

let content = file.data; Let resBlob = new Blob([content]) let reader = new FileReader() readAsText(resBlob, "utf-8") reader.onload = () => { let res = JSON.parse(reader.result) console.log(JSON.parse(reader.result)) }Copy the code