Search code examples
node.jstypescriptwebsocketbufferarraybuffer

Typescript how to use ArrayBuffer data made of JSON


I am receiving ArrayBuffer data from a server via Websocket, and having a trouble converting the incoming data into other form.

Here's the code for the WebSocket:

let ws = new WebSocket('wss://api.example.com/websocket');
ws.binaryType = 'arraybuffer'

And I am printing the incoming data out using:

ws.onmessage = (message) => {
  console.log(message.data);
};

And the result looks something like this:

ArrayBuffer(76) {
  [[Int8Array]], [[Int16Array]], [[Int32Array]], [[UInt8Array]]
}

And the documentation of the API I am using says the following is what I will be seeing, which is not what I am currently seeing:

{
  "market": "United States",
  "current_price": 645.00000000,
  "highest_price": 887.00000000,
  ...
}

How do I convert this incoming data into JSON, or any form that I can use to display on my web application? I have tried things like const data = JSON.parse(JSON.stringify(message.data)); and this returns empty objects.

I have been stuck on this error for days now, can anyone please help?

Thank you!


Solution

  • So the problem was the WebSocket library I was using.

    I was using the 'ws' library, and it seems it cannot recognise data converted via .binaryType.

    Once I removed the library and use the original WebSocket that Node.js provides, everything is good to go.

    I appreciate everyone's try helping me.