【问题标题】:Convert a buffer to string and then convert string back to buffer in javascript将缓冲区转换为字符串,然后在 javascript 中将字符串转换回缓冲区
【发布时间】:2018-02-14 17:53:25
【问题描述】:

我在 NODEJS 中使用 ZLIB 来压缩字符串。在压缩字符串时,我得到一个缓冲区。我想将该缓冲区作为 PUT 请求发送,但 PUT 请求拒绝 BUFFER,因为它只需要 STRING。我无法将 BUFFER 转换为 STRING,然后在接收端我无法解压缩该字符串,因此我可以获得原始数据。我不确定如何将缓冲区转换为字符串,然后将该字符串转换为缓冲区,然后解压缩缓冲区以获取原始字符串。

let zlib = require('zlib');
// compressing 'str' and getting the result converted to string
let compressedString = zlib.deflateSync(JSON.stringify(str)).toString();

//decompressing the compressedString
let decompressedString = zlib.inflateSync(compressedString);

最后一行导致输入无效。

我尝试将“compressedString”转换为缓冲区,然后将其解压缩,但也无济于事。

//converting string to buffer
let bufferedString = Buffer.from(compressedString, 'utf8');
//decompressing the buffer
//decompressedBufferString = zlib.inflateSync(bufferedString);

此代码还给出了异常,因为输入无效。

【问题讨论】:

  • 您尝试过什么,您现在拥有的代码是什么?我们需要Minimal, Complete, Verifiable example 来帮助您解决具体问题。
  • @RickyM 我已经更新了这个问题。你能建议我一些解决方案或解决方法吗?

标签: node.js string compression buffer zlib


【解决方案1】:

我会阅读zlib 的文档,但用法很清楚。

var Buffer = require('buffer').Buffer;
var zlib = require('zlib');

// create the buffer first and pass the result to the stream
let input = new Buffer(str);

//start doing the compression by passing the stream to zlib
let compressedString = zlib.deflateSync(input);

// To deflate you will have to do the same thing but passing the 
//compressed object to inflateSync() and chain the toString()
let decompressedString = zlib.deflateSync(compressedString).toString();

有很多方法可以处理流,但这是您试图通过提供的代码实现的目标。

【讨论】:

  • 我明白这一点,但现在compressedString 是一个缓冲区。我正在使用一个 API,我无法发送缓冲区,我需要发送一个字符串。所以我需要一些方法可以将缓冲区转换为字符串并将其发送到 API,而在接收它的另一端,我需要将字符串转换为缓冲区并解压缩。
  • 您还必须包含已实现的 API 代码,以便我可以更新答案。
  • 我使用的是内部 API,我将无法共享该代码。重要的是它需要一个字符串来传递给它。
  • 从初始压缩解压缩字符串时,我不断收到错误,表明数据损坏。到目前为止,该过程没有任何帮助,因此我建议将缓冲区流式传输到您的 API,而不是传递字符串。否则,最好不要压缩结果以发送并将结果传递给 API。
  • 非常感谢@RickyM。我认为来回转换字符串和缓冲区是不可行的。
【解决方案2】:

尝试将缓冲区作为 latin1 字符串而不是 utf8 字符串发送。例如,如果您的缓冲区位于 mybuf 变量中:

mybuf.toString('latin1');

并将mybuf 发送到您的 API。然后在你的前端代码中你可以做这样的事情,假设你的响应在 response 变量中:

const byteNumbers = new Uint8Array(response.length);
for (let i = 0; i < response.length; i++) {
  byteNumbers[i] = response[i].charCodeAt(0);
}
const blob: Blob = new Blob([byteNumbers], {type: 'application/gzip'});

根据我的经验,与发送缓冲区相比,通过这种方式传输的大小将略高,但至少与 utf8 不同,您可以取回原始二进制数据。我仍然不知道如何使用utf8编码,根据this SO answer这似乎不可能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2019-07-30
    • 2019-07-29
    • 2016-09-23
    • 1970-01-01
    • 2021-01-04
    • 2016-07-29
    相关资源
    最近更新 更多