Similar to Binary Data in JSON String. Something better than Base64 however I'm asking about JS datatypes specifically (like Uint8Array) and don't have a requirement to use JSON.
I have a JS Object
with many nested values including values of type Uint8Array
and ArrayBuffer
that I need to send as an encoded string.
I know I can convert individual fields to strings and then manually decode each specific field on the other end.
That's the approach I'm currently taking - through code like:
export const uInt8ArrayToString = (uInt8Array: Uint8Array) => {
const string: string = utf8Decoder.decode(uInt8Array);
return string;
};
export const arrayBufferToString = (buffer: ArrayBuffer): string => {
return utf8Decoder.decode(new Uint8Array(buffer));
};
And for decoding:
export const stringToUint8Array = (string: string) => {
const uint8Array: Uint8Array = utf8Encoder.encode(string);
return uint8Array;
};
export const stringToArrayBuffer = (string: string) => {
const uint8Array: Uint8Array = utf8Encoder.encode(string);
const arrayBuffer: ArrayBuffer = uInt8ArrayToArrayBuffer(uint8Array);
return arrayBuffer;
};
However this seems somewhat inefficient, as I have to note the data type used by each field and encode/decode specific fields on end/
Can I encode binary JS data - including uIntArrays and ArrayBuffers - to a string format in a single step?