首页 > 解决方案 > 缓冲区到字符串格式错误的编码(本机 ZLIB 压缩 - Node.js)

问题描述

您好,我正在将 JSON 通过 zlib 进行压缩,将其作为缓冲区存储在平面文件数据库中,然后读取并发送出去。

除了我的问题是数据是各种疯狂的字符。我试过 .toString() 我试过 Node 的官方 StringDecoder。我已经尝试了很多东西,但是当我实际上需要输出的最终 JSON 时,除了 .toJSON 可读作为 JSON 缓冲区之外,我似乎无法以任何格式获得它。

想法?

写入平面文件数据库

export const writeCollection = (index, timespan, data) => {
  zlib.gzip(JSON.stringify(data), (err, result) => {
    if (err) {
      console.log({ err });
    } else {
      const keyName = dbCollections.gzip[index].add({
        result
      });
      collectionKeys.gzip[index] = keyName;
      writeLogging(timespan, keyName, index, "gzip");
    }
  });

  zlib.brotliCompress(JSON.stringify(data), (err, result) => {
    if (err) {
      console.log({ err });
    } else {
      const keyName = dbCollections.brotli[index].add({
        result
      });
      collectionKeys.brotli[index] = keyName;
      writeLogging(timespan, keyName, index, "brotli");
    }
  });
};

从平面文件数据库中读取

export const readCollection = (index, encoding) => {
  const encodedRead = encoding.includes("br")
    ? dbCollections.brotli[index].all()
    : dbCollections.gzip[index].all();
  return encodedRead[0].result;
};

尝试转换为 JSON

export const testGetQuakeData = (req, res) => {
  const encoding = req.headers["accept-encoding"];

  try {
    const data = readCollection(0, encoding);
    console.log(data)
    const json = decoder.write(Buffer.from(data));
    console.log(json)
    // res.set({
    //   'Content-Type': 'application/json',
    //   'Content-Encoding': encoding.includes('br') ? 'br' : "gzip",
    // })
    res.send(json)
  } catch (err) {
    console.log({ err });
    res.status(500).send(err);
  }
};

标签: node.jsjsonbufferzlib

解决方案


忘记用 ZLIB 解压了!

 export const testGetQuakeData = (req, res) => {
  const encoding = req.headers["accept-encoding"];

  try {
    const data = readCollection(0, encoding);
    encoding.includes("br")
      ? zlib.brotliDecompress(data, (err, result) => {
          err ? res.status(500).send(err) : res.send(decoder.write(result));
        })
      : zlib.unzip(data, (err, result) => {
          err ? res.status(500).send(err) : res.send(decoder.write(result));
        });
  } catch (err) {
    console.log({ err });
    res.status(500).send(err);
  }
};

这是未来的产品功能!

export const testGetCompressedQuakeData = (req, res) => {
  const encoding = req.headers["accept-encoding"];
  try {
    const data = readCollection(0, encoding);
    encoding.includes("br")
      ? res.writeHead(200, {
          "Content-Type": "application/json",
          "Content-Encoding": "br",
          "Content-Length": data.length,
        })
      : res.writeHead(200, {
          "Content-Type": "application/json",
          "Content-Encoding": "gzip",
          "Content-Length": data.length,
        })
    res.end(data)
  } catch (err) {
    console.log({ err });
    res.status(500).send(err);
  }
};

内容长度 6319 (Brotli) vs 63148 (JSON) Brotli 压缩获胜!


推荐阅读