Binary data in javascript

We will see below concepts in this lesson.
  • Binary data, files
  • ArrayBuffer, binary arrays
  • TextDecoder and TextEncoder
  • Blob
  • File and FileReader
  • typed array

//blob
import {Blob} from 'buffer';

//ArrayBuffer - TypedArrays
let b1 = new Blob(["1", "2", {}, "3456789"]);

console.log("Blob type and size -> ", b1.type, b1.size);

let b2 = new Blob(["<html>…sdsd</html>"], { type: "text/html" });
console.log("Blob type and size -> ", b2.type, b2.size);

//string representation of blob
b2.text().then((text) => console.log("Blob text ", text));

let blob = new Blob(["Hello, world!"], { type: "text/plain" });

// (document.getElementById("l1")).href = URL.createObjectURL(blob);

//Buffer = Using memory efficiently

/* Buffer vs Array
It has a fixed length, we can’t increase or decrease it.
It takes exactly that much space in the memory.
To access individual bytes, another “view” object is needed, not buffer[index]
*/
//8 bytes consecutive memory
const buffer = new ArrayBuffer(8);
console.log("buffer length", buffer.byteLength);

//1 byte view = 8 locations
const view = new Uint8Array(buffer);
console.log("int view8", view[0], view); // 0
console.log("is view Array? -> ", Array.isArray(view)); // false

//2 byte view = 4 locations
let view16 = new Uint16Array(buffer);
console.log("int view16 -> ", view16); // 0

view16[0] = 1120;

console.log("view16 -> ", view16.join("-"));

//Stream

let f = async function () {
  const readableStream = blob.stream();
  const stream = readableStream.getReader();

  while (true) {
    // for each iteration: data is the next blob fragment
    let { done, data } = await stream.read();
    if (done) {
      // no more data in the stream
      console.log("all blob processed.");
      break;
    }

    // do something with the data portion we've just read from the blob
    console.log(data);
  }
};
f();
//b2.stream().getReader().

Web development and Automation testing

solutions delivered!!