websocket nodejs流响应的二进制如何转换?

lskq00tm  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(137)

我让客户端WebSocket连接到第三方WebSocket,WebSocket发送的每个响应的格式如下:

{
  type: 'binary',
  binaryData: <Buffer 1f 8b 08 00 00 00 00 00 00 00 ab 56 4a ce 4f 49 55 b2 32 34 30 30 31 30 d0 51 ca 4c 51 b2 02 12 86 4a 3a 4a b9 c5 e9 40 36 90 51 92 99 9b 5a 5c 92 98 ... 26 more bytes>
}

在API文档中,他们提到所有的响应都被压缩成gzip格式。如何在nodejs中将这些数据转换为可读格式?谢谢

xurqigkl

xurqigkl1#

binaryData实际上是一个gzip数据(基于签名1f 8b)。要修改gzip数据,可以使用以下代码

const zlib = require("zlib");
// yourCompressData in your case should be the binaryData in the question
zlib.gunzip(yourCompressedData, (err, decompressedData) => {
  if (err) {
    console.error("handler errors here :-)", err);
    return;
  }

  // The decompressedData is also a Buffer
  console.log("Decompressed Data:", decompressedData);

  // Convert the Buffer to a string if the uncompress data should be a string
  console.log("Decompressed String:", decompressedData.toString());
});

当然,转换的数据应该是基础的,并由你期望得到的数据处理。例如,如果数据是音频文件,则没有理由将其转换为字符串

相关问题