将缓冲区转换为字符串,然后将字符串转换回JavaScript中的缓冲区



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

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);

最后一行引起的问题,说输入无效。

我试图将"压缩串"转换为缓冲区,然后解压缩,然后也无济于事。

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

此代码也给出了例外,因为输入无效。

我会阅读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();

有多种处理流的方法,但这是您尝试通过提供的代码来实现的。

尝试将缓冲区作为拉丁语字符串而不是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编码来做到这一点,因此答案似乎不可能。

最新更新