如何确定从传递给node.js zlib.inflate的缓冲区读取的字节数?

时间:2013-01-07 13:05:11

标签: javascript node.js zlib

我有一个node.js Buffer实例,其中缓冲区是段的连接​​,每个段都有一个20字节的头,后跟缩小的数据。

我需要的是使用node.js读取缩减的数据,并知道放气的序列有多少字节,这样我才能正确地前进到下一个缓冲区。像这样:

var zlib = require('zlib');
var sections = [];
// A variable named 'buffer' is declared pointing to the Buffer instance
// so I need to read the first section, then the second section etc.
buffer = buffer.slice(20); // skip the 20-byte header
zlib.inflate(buffer, function(err, inflatedData) {
  sections.push(inflatedData);
});
// How many bytes zlib readed from the buffer to
// create the 'inflatedData' instance?
// suppose the number of bytes read is pointed by the variable 'offset',
// then I could do this to read the next section:
buffer = buffer.slice(offset + 20);
zlib.inflate(buffer, function(err, inflatedData) {
  sections.push(inflatedData);
});

2 个答案:

答案 0 :(得分:2)

NodeJS文档不明确。只需添加:{ info: true },返回对象将是一个带有带解压缩数据的缓冲区和引擎的对象。例如:

const result = zlib.inflateRawSync(compressed, { info: true } as any) as any;
const bytesRead = result.engine.bytesWritten;  // "bytesWritten" is actually "compressedSize".

如果使用打字稿,则需要强制转换为“ any”,因为@ types / node @ 14尚未指定此选项。

答案 1 :(得分:0)

// How many bytes zlib readed from the buffer to
// create the 'inflatedData' instance?

答案:所有人。

buffer.slice(20)将从位置20直到缓冲区结束。这就是zlib.inflate()方法得到的结果,这就是它处理的内容。

也许这会有所帮助:https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem

你好像很困惑。你究竟想做什么? (也就是说,你想解决什么问题?)