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.
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.
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();encoding: gzip
body: hello from a gzipped servercreateGunzip 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.