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.
npm install gzip-sizeimport { 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"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));
//=> 78Gzip Size provides three complementary API patterns for different use cases:
gzipSizegzipSizeSyncgzipSizeFromFilegzipSizeFromFileSyncgzipSizeStreamThe library uses Node.js built-in
zlibCalculate 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);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 });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`);
});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;
}All functions accept an optional
optionslevelchunkSizewindowBitsmemLevel// 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);Based on the implementation:
gzipSizenullundefinedgzipSizeSynczlib.gzipSyncgzipSizeFromFilegzipSizeFromFileSyncfs.readFileSyncgzipSizeSyncgzipSizeStreamwrapper.gzipSizetry {
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);
});Requires Node.js version:
^12.20.0 || ^14.13.1 || >=16.0.0This package uses ES modules and requires Node.js environments that support native ES module imports.