or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Gzip Size

Gzip Size is a Node.js utility library for calculating the gzipped size of strings, buffers, and files. It provides both synchronous and asynchronous APIs for determining compressed sizes without actually writing files to disk, supporting all standard zlib compression options including customizable compression levels.

Package Information

  • Package Name: gzip-size
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation:
    npm install gzip-size

Core Imports

import { gzipSize, gzipSizeSync, gzipSizeFromFile, gzipSizeFromFileSync, gzipSizeStream } from "gzip-size";

For TypeScript with type imports:

import { gzipSize, gzipSizeSync, gzipSizeFromFile, gzipSizeFromFileSync, gzipSizeStream, type Options, type GzipSizeStream } from "gzip-size";

Note: This package uses ES modules (

"type": "module"
) and does not support CommonJS require().

Basic Usage

import { gzipSize, gzipSizeSync } from "gzip-size";

const text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.';

console.log(text.length);
//=> 191

console.log(await gzipSize(text));
//=> 78

console.log(gzipSizeSync(text));
//=> 78

Architecture

Gzip Size provides three complementary API patterns for different use cases:

  • Functional API: Direct functions (
    gzipSize
    ,
    gzipSizeSync
    ) for simple string/buffer compression analysis
  • File System Integration: File-specific functions (
    gzipSizeFromFile
    ,
    gzipSizeFromFileSync
    ) that read and analyze files directly
  • Stream Processing: Transform stream (
    gzipSizeStream
    ) for pipeline integration and real-time analysis
  • Sync/Async Patterns: All core operations available in both synchronous and asynchronous variants

The library uses Node.js built-in

zlib
module for compression with sensible defaults (compression level 9) while allowing full customization through options.

Capabilities

String and Buffer Compression

Calculate the gzipped size of strings or Buffer objects.

/**
 * Get the gzipped size of a string or buffer (async)
 * @param input - String or Buffer to compress
 * @param options - Optional zlib compression options
 * @returns Promise resolving to compressed size in bytes
 */
function gzipSize(input: string | Buffer, options?: Options): Promise<number>;

/**
 * Synchronously get the gzipped size of a string or buffer
 * @param input - String or Buffer to compress  
 * @param options - Optional zlib compression options
 * @returns Compressed size in bytes
 */
function gzipSizeSync(input: string | Buffer, options?: Options): number;

Usage Examples:

import { gzipSize, gzipSizeSync } from "gzip-size";

// Async version
const size = await gzipSize("Hello world!");
console.log(size); // e.g., 23

// Sync version
const sizeSync = gzipSizeSync("Hello world!");
console.log(sizeSync); // e.g., 23

// With compression options
const highCompression = await gzipSize("Some text", { level: 9 });
const lowCompression = await gzipSize("Some text", { level: 1 });
console.log(highCompression < lowCompression); // true

// Buffer input
const buffer = Buffer.from("Buffer content");
const bufferSize = gzipSizeSync(buffer);

File-based Compression Analysis

Calculate the gzipped size of files directly from the filesystem.

/**
 * Get the gzipped size of a file (async)
 * @param filePath - Path to file to analyze
 * @param options - Optional zlib compression options
 * @returns Promise resolving to compressed size in bytes
 */
function gzipSizeFromFile(filePath: string, options?: Options): Promise<number>;

/**
 * Synchronously get the gzipped size of a file
 * @param filePath - Path to file to analyze
 * @param options - Optional zlib compression options  
 * @returns Compressed size in bytes
 */
function gzipSizeFromFileSync(filePath: string, options?: Options): number;

Usage Examples:

import { gzipSizeFromFile, gzipSizeFromFileSync } from "gzip-size";

// Async file analysis
const fileSize = await gzipSizeFromFile('./large-file.txt');
console.log(`Compressed size: ${fileSize} bytes`);

// Sync file analysis  
const fileSizeSync = gzipSizeFromFileSync('./package.json');
console.log(`Package.json compressed: ${fileSizeSync} bytes`);

// With compression options
const optimizedSize = await gzipSizeFromFile('./bundle.js', { level: 9 });

Stream-based Processing

Create a transform stream that calculates gzip size while passing data through unchanged.

/**
 * Create a transform stream that calculates gzip size
 * @param options - Optional zlib compression options
 * @returns GzipSizeStream - A PassThrough stream with gzip size functionality
 */
function gzipSizeStream(options?: Options): GzipSizeStream;

interface GzipSizeStream extends PassThroughStream {
  /** Contains the gzip size after stream completion */
  gzipSize?: number;
  
  /** Event listeners for gzip-size event */
  addListener(event: 'gzip-size', listener: (size: number) => void): this;
  on(event: 'gzip-size', listener: (size: number) => void): this;
  once(event: 'gzip-size', listener: (size: number) => void): this;
  emit(event: 'gzip-size', size: number): boolean;
  // ... other event methods for 'gzip-size' event
}

Usage Examples:

import fs from 'node:fs';
import { gzipSizeStream } from "gzip-size";

// Stream with event listener
const stream = fs.createReadStream('input.txt')
  .pipe(gzipSizeStream())
  .pipe(fs.createWriteStream('output.txt'));

stream.on('gzip-size', (size) => {
  console.log(`Gzipped size: ${size} bytes`);
});

stream.on('end', () => {
  console.log(`Final size: ${stream.gzipSize} bytes`);
});

// Passthrough usage - data flows unchanged
let outputData = '';
fs.createReadStream('data.txt')
  .pipe(gzipSizeStream({ level: 6 }))
  .on('data', (chunk) => {
    outputData += chunk; // Original data unchanged
  })
  .on('gzip-size', (size) => {
    console.log(`Compressed size would be: ${size} bytes`);
  });

Types

import { Buffer } from 'node:buffer';
import { PassThrough as PassThroughStream } from 'node:stream';
import { ZlibOptions } from 'node:zlib';

/** Type alias for Node.js zlib compression options */
type Options = ZlibOptions;

/** Enhanced PassThrough stream with gzip size functionality */
interface GzipSizeStream extends PassThroughStream {
  /** Contains the gzip size of the stream after completion */
  gzipSize?: number;
  
  // Event method overloads for 'gzip-size' event
  addListener(event: 'gzip-size', listener: (size: number) => void): this;
  on(event: 'gzip-size', listener: (size: number) => void): this;
  once(event: 'gzip-size', listener: (size: number) => void): this;
  removeListener(event: 'gzip-size', listener: (size: number) => void): this;
  off(event: 'gzip-size', listener: (size: number) => void): this;
  emit(event: 'gzip-size', size: number): boolean;
  prependListener(event: 'gzip-size', listener: (size: number) => void): this;
  prependOnceListener(event: 'gzip-size', listener: (size: number) => void): this;
}

Configuration Options

All functions accept an optional

options
parameter that supports any Node.js zlib options:

  • level
    : Compression level from 1 (fastest) to 9 (best compression). Default: 9
  • chunkSize
    : Chunk size for processing. Default: 16384
  • windowBits
    : Window size parameter. Default: 15
  • memLevel
    : Memory usage level from 1 to 9. Default: 8
  • Plus all other standard zlib options
// Example with various compression options
const options = {
  level: 6,           // Balanced compression
  chunkSize: 8192,    // Smaller chunks
  memLevel: 9         // Higher memory usage
};

const size = await gzipSize(data, options);

Error Handling

Based on the implementation:

  • gzipSize
    : Returns 0 for falsy input (like
    null
    ,
    undefined
    , empty string), follows zlib error patterns for compression errors
  • gzipSizeSync
    : Throws synchronously for compression errors (via
    zlib.gzipSync
    )
  • gzipSizeFromFile
    : Promise rejects on file read errors or compression errors
  • gzipSizeFromFileSync
    : Throws synchronously for file or compression errors (via
    fs.readFileSync
    and
    gzipSizeSync
    )
  • gzipSizeStream
    : Emits error events on stream or compression failures; sets
    wrapper.gzipSize
    to 0 specifically on gzip compression errors
try {
  const size = await gzipSizeFromFile('nonexistent.txt');
} catch (error) {
  console.error('File not found or compression error:', error);
}

const stream = gzipSizeStream();
stream.on('error', (error) => {
  console.error('Stream error:', error);
});

Node.js Compatibility

Requires Node.js version:

^12.20.0 || ^14.13.1 || >=16.0.0

This package uses ES modules and requires Node.js environments that support native ES module imports.