koolaang
koolaang

Reputation: 417

How to convert text to ArrayBuffer like responseType of ArrayBuffer in Javascript

I am using a library to make an HTTP call, I know it is using XMLHTTPRequest, but I can't set responseType and response is always text.

I need to convert the text to ArrayBuffer as I used responseType: ArrayBuffer. I tried multiple conversion but none of them produce the same buffer.

Update: So the code below is what converts the ArrayBuffer to the string.

    var dataView = new DataView(this.response);
    var decoder = new TextDecoder('utf8');
    var decodedString = decoder.decode(dataView);

I need to reverse this

   var encodedr = new TextEncoder('utf8');              
   var encodedArray =encodedr.encode(req.body);
   var arrayBuffer = encodedArray.buffer;

is not the same and is almost twice the size.

Update 2: Glitch with code example https://successful-pepper.glitch.me/

Upvotes: 2

Views: 1207

Answers (1)

The GTMD
The GTMD

Reputation: 148

The only issue I see in the glitch you've posted is that you're trying to compare 2 ArrayBuffers by reference, and not by value.

In JavaScript, non-primitive values are given a reference in the memory. So, when comparing non-primitive values, their reference in the memory is being compared instead of their value.

A simple exaple:

var firstArray = [1, 2, 3];
var secondArray = [1, 2, 3];

console.log(firstArray === secondArray); // prints: false

You can try to use JSON.stringify() to convert both ArrayBuffers to JSON and compare these values. You will, then, get that both ArrayBuffers are the same.

Another way to test if two ArrayBuffers are the same can be found here: How to test for equality in ArrayBuffer, DataView, and TypedArray

Upvotes: 1

Related Questions