简体   繁体   中英

How to determine the number of bytes read from buffer passed to node.js zlib.inflate?

I have a node.js Buffer instance, where the buffer is a concatenation of sections, and each section has a 20 byte header followed by deflated data.

What I need is to read the deflated data using node.js, and know how many bytes the deflated sequence had so I can properly advance to the next buffer section. Something like this:

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

NodeJS documentation is not clear. Just add: { info: true } , and the return object will be an object with a buffer with the decompressed data, and an engine. Eg:

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

If using typescript, you'll need to cast to "any", because @types/node@14 does not specify this option yet.

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

Answer: All of them.

buffer.slice(20) will be from position 20 until the end of the buffer. That's what the zlib.inflate() method got, so that's what it processed.

Maybe this would be helpful: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem

You seem like you might be confused. What are you actually trying to do? (That is, what problem are you trying to solve?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM