HTTP Response Decompression Utility

10.0.0 · active · verified Tue Apr 21

Decompress-response is a focused utility package designed to automatically decompress HTTP `IncomingMessage` streams based on their `Content-Encoding` header. It supports common compression algorithms including `gzip`, `deflate`, `brotli`, and `zstd` (added in v10.0.0). Currently at stable version 10.0.0, released in late 2023, the package follows a release cadence tied to Node.js LTS updates, with major versions often introducing increased Node.js engine requirements. A key differentiator is its straightforward, single-function API that transforms an `http.IncomingMessage` stream into a decompressed stream, making it easy to integrate. It is notably used internally by popular HTTP client libraries like `got` and operates as a pure ECMAScript Module (ESM) package since version 8, requiring modern JavaScript module syntax for usage.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to set up a basic Node.js server that sends a gzipped response, and then how a client can use `decompress-response` to automatically decompress and consume the HTTP stream.

import http from 'node:http';
import zlib from 'node:zlib';
import decompressResponse from 'decompress-response';

// Create a simple HTTP server to simulate a compressed response
const server = http.createServer((request, serverResponse) => {
  if (request.url === '/compressed-data') {
    serverResponse.writeHead(200, {
      'Content-Type': 'text/plain',
      'Content-Encoding': 'gzip' // Indicate gzipped content
    });
    // Compress the response body
    zlib.gzip('Hello from decompress-response! This is some example text to be decompressed.', (error, buffer) => {
      if (error) {
        console.error('Error gzipping:', error);
        serverResponse.end('Error gzipping content');
        return;
      }
      serverResponse.end(buffer);
    });
  } else {
    serverResponse.end('Not found');
  }
});

server.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');

  // Client-side usage: Fetch and decompress the response
  http.get('http://localhost:3000/compressed-data', response => {
    console.log('Original response headers:', response.headers);

    let decompressedResponse = decompressResponse(response);
    let data = '';

    decompressedResponse.on('data', chunk => {
      data += chunk.toString();
    });

    decompressedResponse.on('end', () => {
      console.log('Decompressed data:', data); // Should print 'Hello from decompress-response! ...'
      server.close(); // Clean up the server after the request
    });

    decompressedResponse.on('error', error => {
      console.error('Error during decompression:', error);
      server.close();
    });
  }).on('error', error => {
    console.error('HTTP GET request error:', error);
    server.close();
  });
});

view raw JSON →