Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use browser's native gzip decompression using Javascript?

The backend server responds with a gzip file but without the Content-Encoding: gzip header. And I do not have control over the server so can't handle the issue server side.

What I need now is to decompress the gzipped file client side using javascript.

I have found this excellent library which can help me do this: http://nodeca.github.io/pako/

But I don't want to add additional library just to un-gzip a file. I feel that there should be a way to use the browser's native functionality to un-gzip. Am I correct? If I am wrong can someone explain why this browser functionality is not exposed as a javascript API? And is there a way to un-gzip a file in javascript without adding an additional library?

like image 640
Yash Agarwal Avatar asked Mar 23 '16 17:03

Yash Agarwal


People also ask

Do browsers automatically decompress gzip?

gzip is commonly supported by web servers and modern browsers, meaning that servers can automatically compress files with gzip before sending them, and browsers can uncompress files upon receiving them.

What is gzip in JavaScript?

gzip-js is a pure JavaScript implementation of the GZIP file format. It uses the DEFLATE algorithm for compressing data. Please note that since this is a pure JavaScript implementation, it should NOT be used on the server for production code. It also does not comply 100% with the standard, yet.

Do all browsers support gzip?

All modern browsers can handle a gzip encoded response. In fact, if you look at their requests, they'll have a header that says something along the lines of Accept-Encoding: gzip which is their way of saying to the server that they can handle gzipped responses.

How does browser gzip work?

Using gzip on the WebWhen a browser with gzip support sends a request, it adds “gzip” to its Accept-Encoding header. When the web server receives the request, it generates the response as normal, then checks the Accept-Encoding header to determine how to encode the response.


1 Answers

The Compression Streams API is a new web standard and is currently available in Chrome (since v80), Edge, and Deno. Other browsers will eventually add it, but in the mean time the best bet is a WASM implementation. Apparently WASM implementations can approach 90% of the performance of a native implementation (and ~20x the speed of a JS implementation).

Some example usage of the Compression Streams API:

async function decompressBlob(blob) {
  let ds = new DecompressionStream("gzip");
  let decompressedStream = blob.stream().pipeThrough(ds);
  return await new Response(decompressedStream).blob();
}

And for compression:

const compressedReadableStream = inputReadableStream.pipeThrough(new CompressionStream('gzip'));

More info:

  • WICG standards doc
like image 191
joe Avatar answered Oct 14 '22 03:10

joe