You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何将WebSocket返回的Gzip二进制Buffer转为可读格式?

在Node.js中解压WebSocket返回的Gzip二进制数据

核心思路

Node.js内置的zlib模块原生支持Gzip格式的解压操作,只需将WebSocket响应中的binaryData Buffer传入对应方法,即可转换为可读内容。

代码实现

1. 异步解压(推荐生产环境使用)

异步方式不会阻塞事件循环,适合大多数场景:

const zlib = require('zlib');

// 假设wsResponse是WebSocket返回的响应对象
const wsResponse = {
  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 ...>
};

zlib.gunzip(wsResponse.binaryData, (err, decodedBuffer) => {
  if (err) {
    console.error('解压失败:', err);
    return;
  }
  // 转换为UTF-8字符串(根据实际数据编码调整)
  const readableContent = decodedBuffer.toString('utf8');
  console.log('解压后的可读内容:', readableContent);

  // 如果返回的是JSON格式,直接解析
  try {
    const parsedData = JSON.parse(readableContent);
    console.log('解析后的JSON数据:', parsedData);
  } catch (parseErr) {
    console.error('JSON解析失败:', parseErr);
  }
});

2. 同步解压(仅适用于小数据量)

若数据体积很小,可使用同步方法简化代码:

const zlib = require('zlib');

try {
  const decodedBuffer = zlib.gunzipSync(wsResponse.binaryData);
  const readableContent = decodedBuffer.toString('utf8');
  console.log('解压后的内容:', readableContent);
} catch (err) {
  console.error('解压失败:', err);
}

3. 流式处理(针对超大二进制数据)

当返回数据体积过大时,流式处理能有效控制内存占用:

const zlib = require('zlib');
const { PassThrough } = require('stream');

const inputStream = new PassThrough();
inputStream.end(wsResponse.binaryData);

const gunzipStream = zlib.createGunzip();

inputStream.pipe(gunzipStream)
  .on('data', (chunk) => {
    // 处理逐块解压的内容
    console.log('解压片段:', chunk.toString('utf8'));
  })
  .on('end', () => {
    console.log('流式解压完成');
  })
  .on('error', (err) => {
    console.error('流式解压出错:', err);
  });

注意事项

  • 确认binaryData是标准的Gzip压缩Buffer,否则会触发解压错误。
  • 根据服务返回的实际数据类型调整编码(如ascii、base64等),若为二进制文件则无需转换为字符串。

内容的提问来源于stack exchange,提问作者user15450241

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:46:24