javascriptnode.jscompressionzlibfflate

Mixing zlib and fflate for compression in JavaScript?


I'm trying to use fflate to decompress data compressed by zlib

The data was compressed by using a zlib stream, and if I use zlib to inflate the data back, it works.

The Script:

import Zlib from 'zlib';

const gz = Zlib.createGzip({
   flush: Zlib.constants.Z_FINISH,
});
gz.on('error', function(err){    console.log(err.stack);   });
gz.pipe(out, { end: false });
gz.end(Buffer.from(JSON.stringify(msg)))

However, I want to use fflate to inflate the data (later I will do it on the client, but for testing I'm doing it in the same script).

The Script:

import { unzlibSync, strFromU8 } from 'fflate';

var uint8array = toUni8Array(dataFromStream);    
const dd = strFromU8(unzlibSync(uint8array))
console.log(dd.toString())

The code above throws an invalid zlib data error when passed data from zlib, but works with data encoded by fflate.

So the bottom line is: If I encode and decode the data with the same library everything works just fine, but the combination of both libraries doesn't work.

Does it require any specific configuration to get them to work together?


Solution

  • unzlibSync is almost certainly looking for a zlib stream, but you are giving it a gzip stream. Use gunzipSync instead.