Extract Gzip data in Javascript


Hello seekers! Hope you are having a great day. In this blog, let me explain how to effectively extract gzip data using Javascript.

What is a Gzip file ?

Gzip is a file format that is used to compress and decompress files. It is based on the deflate algorithm, which compresses data in order to pace up network transfers. For Linux systems, it is the standard file compression format and it is much faster than ZIP.

Gzip extraction in Javascript

Gzip aggressively compresses large amounts of data into smaller files. Extracting this data in other platforms such as Node JS is comparatively easier. However, you cannot use any default methods and libraries in javascript. No matter, the pako library just serves the purpose. Let’s take a look at how to use this extraction procedure in depth.

First of all, we need to link the pako library’s CDN with the script tag in the html file as follows:

<script type="text/javascript" src="../js/pako.min.js"></script>

Write a JS method that retrieves the gzip file from the server and converts it into a blob. You can use Ajax, fetch or JSZip for fetching and loading the file. Once the file is loaded, we will transform the file into a blob and the blob’s array buffer has to be converted into a Uint8Array.

After that, we will pass this result to pako’s ungzip method which returns the data in its original format. In the below sample code, the variable parsed will store the extracted data.

JSZip.loadAsync(data)then(function (zip) {

   var file = zip.file(/zip/);

   return file.async("blob");

}}).then(async function success(text) {

var fileReader = await text.arrayBuffer();

      const binData = new Uint8Array(fileReader);

      var parsed = pako.ungzip(binData,{ 'to': 'string' });

});

That’s it, you can extract uncompressed data from gzip files in pure JS with these simple steps. Now that you can extract gzip easily, you can compress your large downloadable files in gzip format to reduce download time and data usage. Word of caution, make sure the compression level of your downloadable gzip matches with the compression level of your pako code.

You can change the compression level as follows:

pako.ungzip(data, {level: 4, to: 'string'});

To explore more about pako library and it’s usage, visit this documentation page.

Leave A Comment

Your email address will not be published. Required fields are marked *