Eternity
Eternity

Reputation: 111

What's the clean method to build binary buffer in JS?

I need to build a binary buffer consisting from various components, concretely several strings and ArrayBuffer (or UINT8Array derived from it) inserted between the string sequences. Ideally by creating an empty buffer and sequentially appending to it everything needed and in the finish get the accumulated buffer.

My question is how to properly do that, what data type to use for it, and finally how to pass the resulting buffer as raw sequence of bytes to GM_xmlhttpRequest.data property. if it deals only the strings I'm able to concatenate them and pass the resulting string, but clueless how to get content of the data represented by ArrayBuffer object.

Upvotes: 1

Views: 217

Answers (1)

anthumchris
anthumchris

Reputation: 9072

An ArrayBuffer cannot be accessed directly and you can use TypedArray views or DataView objects to manipulate the buffer's byte values. You can use TextEncoder and TextDecoder for easier manipulation of text backed by ArrayBuffers.

Consider using fetch(), which is more performant that the older XMLHttpRequest ways. An ArrayBuffer must be serialized to a string to send in an HTTP request.

const encoder = new TextEncoder();
const encoded = encoder.encode('hello');
const serialized = encoded.toString();
fetch('https://example.com', {
  method: 'post',
  body: serialized
})

Upvotes: 1

Related Questions