Single API to compress them all
Lets learn how to use Compressions Stream API
Downloading large files can be a pain, but it doesn't have to be. With the new Compression Stream API, we can compress files for download or download large files efficiently. This micro-blog will teach you how.
Compression Stream API
Compression Stream API recently got stable and we can now use it on any browser to compress any file, what we have to do is follow these 4 simple steps:
Convert your file into a ReadableStream, you can do this by using Fetch API or using FileReader etc.
let readableStream = await fetch("./file.js").then((res) => res.body);
Then we have to pipe this stream through a CompressionStream.
let compressedReadableStream = readableStream.pipeThrough( new CompressionStream("gzip") );
Then create a Response object of this compressed stream which will help us to convert it to a blob later.
let response = new Response(compressedReadableStream);
Finally, Convert the response into a blob to use it however you want.
let blob = await response.blob();
Now you can use this blob to either download the compressed file or store it somewhere....
let dataURL = window.URL.createObjectURL(blob); let a = document.createElement("a"); a.href = dataURL; a.download = "file.gz"; a.click();
complete code👇.