Guide on utilizing DecompressionStream for decompressing a GZIP file with JavaScript in a web browser

Every major web browser now has built-in support for the DecompressionStream API. Despite this, I'm struggling to utilize it with fetch() in order to decompress a gzip file directly within the browser.

The code below successfully decompresses a base64 string:

const decompress = async (url) => {
  const ds = new DecompressionStream('gzip');
  const response = await fetch(url);
  const blob_in = await response.blob();
  const stream_in = blob_in.stream().pipeThrough(ds);
  const blob_out = await new Response(stream_in).blob();
  return await blob_out.text();
};

decompress(
  'data:application/octet-stream;base64,H4sIAAAAAAAAE/NIzcnJVyjPL8pJAQBSntaLCwAAAA=='
).then((result) => {
  console.log(result);
});

However, when attempting to use the same function on a hello.txt.gz file created using gzip hello.txt on MacOS (where hello.txt contains "hello world"), an Error is thrown.

decompress('/hello.txt.gz').then((result) => {
  console.log(result);
});
# FireFox
Failed to read data from the ReadableStream: “TypeError: The input data is corrupted: incorrect header check”.
Uncaught (in promise) DOMException: The operation was aborted.

# Chrome
Uncaught (in promise) TypeError: Failed to fetch

# Safari
[Error] Unhandled Promise Rejection: TypeError: TypeError: Failed to Decode Data.
[Error] Unhandled Promise Rejection: TypeError: Failed to Decode Data.

Edit

A demonstration of the issue can be found at Stackblitz.

Answer №1

With the assistance of @kaiido (found in the question comments), it was determined that the Vite server is responsible for causing this error. The development server is serving .gz files with incorrect headers.

"content-encoding": "gzip"
​​"content-length": "42"
"content-type": "text/plain"

A temporary solution is to change the file extension to something different (for example, from hello.txt.gz to hello.txt.gzip).

Relevant Vite Issues

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that Heroku is using a designated version of Node.js

My node.js application runs perfectly fine on my local machine, but I encounter an error when I deploy it to Heroku: 2012-04-11T00:42:55+00:00 app[web.1]: throw e; // process.nextTick error, or 'error' event on first tick 2012-04-11T00:4 ...

Alert: Parser error in JSONP!

$.ajax({ type: "GET", dataType: "jsonp", jsonpCallback: "jsoncallback", //async: true , data: { // some other data here }, url: "http://mywebsite.com/getRequest.php", success: function(response ...

How can I dynamically adjust the height of a textarea to accommodate varying lengths of

I've designed a textarea that displays personalized text. My goal is to make it adjust its size based on the amount of text, without requiring any scrollbars (unless it reaches a specific height). Additionally, I prefer not to allow users to manually ...

What is preventing me from updating the value of a variable in this manner?

Trying to understand the reason behind an issue with overwriting a value passed to an angularJS directive using an isolate scope (@). When attempting to change the value of vm.index with the following: vm.index = parseInt(vm.index, 10) It does not seem t ...

Creating separate files for interface declarations

Consider a scenario where there is a file named user.ts containing the following declaration: export interface User { userName: string; } The task at hand is to import this particular interface from another TypeScript script. However, due to JavaScript ...

Break up the combined result set into individual rows

In my stored procedure, I am processing records from specific tables. As part of this process, I am using a temporary table to store results generated by join operations. Let's take a look at the structure of Table A: +----+------+--------+ | id | n ...

Remove duplicate values from ng-options

Check out this plunker example I have a collection of cars and their corresponding available years: ["Volvo", "VW", "Audi"] --> [2006, 2007, 2008] ["Ford", "Honda", "Jaguar"] --> [2008, 2009, 2010, 2011] Note: The year 2008 is duplicated. This ...

The functionality for making a GET request in a React Component is not functioning as

I have successfully imported the axios library and React. In a React component, I am making a GET call which is returning a response like this: {"functionality": [ {"category": "", "price": 2.0, "moltiplicator": 100.0, "name": "Plat"} ] } How ...

Convert JavaScript object into distinct identifier

I have a data object where I'm storing various page settings, structured like this: var filters={ "brands":["brand1","brand2","brand3"], "family":"reds", "palettes":["palette1","palette2","palette3"], "color":"a1b2" }; This object is ...

Restrict the number of rows in a real-time search JSON data by utilizing the $.each method

Is there a way to limit the number of rows returned in live search JSON data through URL? I attempted to count the table rows and return false, but it did not work. Any suggestions on how to achieve this? $(document).ready(function() { $.ajaxSetup ...

Discord between Bootstrap tabs and C3 charts: A Compatibility Str

On my website, I have implemented Bootstrap navigation tabs that each contain a chart. The issue I am facing is that when I navigate to the home page, the chart in the active tab displays perfectly fine. However, for the other tabs, the charts overlap with ...

Could a class method be accessed from outside a nested handler method in JavaScript?

I am trying to make an XMLHttpRequest to a server using JavaScript. In the handler function, I need to call a method from the surrounding class. Is there a way to achieve this? Understanding how this works in JavaScript can be confusing. I have experiment ...

If admin access is enabled, the routing will be affected

Within my application, I have implemented 3 different access levels. To grant the admin access to all pages, I inserted the following code in the admin section: else if (claims.admin) { return next() } This configuration successfully allows the admin ...

verify this condition prior to executing the for loop in javascript

When working with a queue in Typescript (ES6) set to run on an interval of 1 ms, it's important to consider the most efficient approach for performance. 1. setInterval(() => { //if (this._queue.filter(a => !a.running && a.cbs.length) ...

Set the display property of all child elements within the DIV to none

CSS <div class="container"> <span></span> <input type="text"> </div> JavaScript function hideElements(){ let container = document.querySelector(".container"); let elements = ...

Intellisense in VSCode is failing to suggest subfolder exports

In my setup, I have a repository/module specifically designed to export TypeScript types into another project. Both of these projects are using TypeScript with ECMAScript modules. The relevant part of the tsconfig.json configuration is as follows: "ta ...

Encountered AxiosError: parameters need to be in the form of an object: 'ERR_BAD_OPTION_VALUE'

I am facing a challenge with passing an array as a parameter in an axios get request within a React application using the latest packages. Despite trying various solutions from similar issues, I have experimented with two different methods/syntax forms, a ...

Is there a way to terminate API requests within my ngrx effect?

When working on a single page, I often trigger multiple actions to initiate search requests to the same API endpoint. Within my effects setup, I have an effect specifically for handling these requests. It looks something like this: runSearchSuccess$ = ...

Implementing a Node-RED flow to interact with MongoDB using a JavaScript object

As part of a school exercise and my personal project, I am working on setting up a NodeRed server that retrieves weather data, stores it in MongoDB, and retrieves it for future searches on the same location. My NodeRed server is attempting to perform a re ...

Attempting to display my ejs template from a node server following the activation of a delete button, all without utilizing ajax

I have created a basic blog application using node.js for the backend and ejs for the frontend. Posting blogs using a web form works well by calling a post route. Now, I am facing an issue with implementing a delete button for each blog post. The current s ...