Search code examples
javascriptzipgzip

How can unzip data using vanilla js?


I have data that is zipped using zlib in NodeJS. I need to unzip this data in vanilla js without using zlib. I have to use another library smaller than zlib if I must use a library to unzip.

I tried to unzip it with pako.js and fflate.js e.g.

var zippedData = '333080002363534b206588c43642621b23b14d90d8a6486c33181b00ccbe314454000000'
var buff = fflate.strToU8(zippedData)

var unzippedData = fflate.gunzipSync(buff)

If I run this code, it responds 'invalid gzip data'. Also, I tried these functions instead of gunzipSync. decompressSync, unzlibSync and the response is the same 'invalid zlib data' or 'invalid gzip data'

enter image description here

I can see my desired result if I add '1f8b0800000000000000' this 10 bytes to the beginning of zipped data and try to unzip with this tool CyberChef that's in the pic.


Solution

  • I think there is a mistake in your zipped sequence

    If it is supposed to be hexadecimal symbols, I would expect a mixture of about 6/16, i.e. 3/8's of the characters, being "a"-"f", but there are surprisingly few.

    On the other hand, if it is supposed to be a string, it is even more unlikely that all characters are within 0-9 and a-f!

    The first debugging steps I suggest are:

    1. Verify that it is correct zipped output, i.e. demonstrate it being created from the input string by zlib? A screenshot would demonstrate it.

    2. Verify that zlib can unzip it. If zlib zipped it but zlib cannot unzip it, nothing else will. A screenshot of zlib unzipping it would convince me.

    I do think the original zipped sequence is not correct.

    If your zippedData is supposed to be data that has already been zipped, why are you passing it in to fflate.strToU8, whose purpose is to Zip a string?

    From https://github.com/101arrowz/fflate

    Using strings is easy with fflate's string conversion API:
    
    const buf = fflate.strToU8('Hello world!');
    
    // The default compression method is gzip
    // Increasing mem may increase performance at the cost of memory
    // The mem ranges from 0 to 12, where 4 is the default
    const compressed = fflate.compressSync(buf, { level: 6, mem: 8 });
    
    // When you need to decompress:
    const decompressed = fflate.decompressSync(compressed);
    const origText = fflate.strFromU8(decompressed);
    console.log(origText); // Hello world!