Skip to content
jshacks.dev
Node.js

Gunzip an HTTP response stream

Decompress a gzip HTTP response from http.get by piping it through zlib.createGunzip with stream pipeline, and why fetch needs none of this. Node.js 24.

2 min read
Summarize in AI

http.get hands you the response bytes exactly as the server sent them, compressed or not. If you ask for gzip, you also have to undo it.

gunzip.mjsJavaScript
import http from 'node:http';
import zlib from 'node:zlib';
import { once } from 'node:events';
import { pipeline } from 'node:stream/promises';

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'content-encoding': 'gzip' });
  res.end(zlib.gzipSync('hello from a gzipped server'));
});
server.listen(0);
await once(server, 'listening');

const req = http.get({ port: server.address().port, headers: { 'accept-encoding': 'gzip' } });
const [res] = await once(req, 'response');
console.log('encoding:', res.headers['content-encoding']);

const chunks = [];
await pipeline(res, zlib.createGunzip(), async (source) => {
  for await (const chunk of source) chunks.push(chunk);
});
console.log('body:', Buffer.concat(chunks).toString());
server.close();
Text
encoding: gzip
body: hello from a gzipped server

createGunzip is a transform stream, so the body is decompressed chunk by chunk as it arrives, and pipeline passes an error from any stage, such as a truncated gzip body, to the awaited promise. The last stage is an async function that reads the decompressed stream. See zlib.

Check content-encoding before you pipe in real code: a server may ignore your accept-encoding and send plain bytes, or send br or deflate, which need createBrotliDecompress or createInflate. None of this applies to fetch, which decompresses for you and would turn a manual gunzip into an "incorrect header check" error.

Also inAsync
Taggednode 24
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.