How to Use gzip in Node.js for Compression
In Node.js, you can use the built-in
zlib module to compress data with gzip. Use zlib.createGzip() to create a gzip transform stream that compresses data when piped through it.Syntax
The main method to use gzip compression in Node.js is zlib.createGzip(). It returns a transform stream that compresses data piped into it.
zlib.createGzip([options]): Creates a gzip compression stream.options: Optional settings like compression level.- Use with streams: pipe readable data into gzip stream, then pipe to writable destination.
javascript
import { createGzip } from 'zlib'; const gzip = createGzip();
Example
This example compresses a text file input.txt into input.txt.gz using gzip streams. It shows how to use fs.createReadStream, zlib.createGzip, and fs.createWriteStream together.
javascript
import { createReadStream, createWriteStream } from 'fs'; import { createGzip } from 'zlib'; const input = createReadStream('input.txt'); const output = createWriteStream('input.txt.gz'); const gzip = createGzip(); input.pipe(gzip).pipe(output); output.on('finish', () => { console.log('File successfully compressed'); });
Output
File successfully compressed
Common Pitfalls
- Not handling stream errors can cause silent failures; always listen for
errorevents on streams. - Trying to gzip data without streams can be inefficient for large files.
- For HTTP responses, set the correct
Content-Encoding: gzipheader when sending compressed data.
javascript
import { createReadStream, createWriteStream } from 'fs'; import { createGzip } from 'zlib'; const input = createReadStream('input.txt'); const output = createWriteStream('input.txt.gz'); const gzip = createGzip(); // Wrong: no error handling input.pipe(gzip).pipe(output); // Right: add error handlers input.on('error', (err) => console.error('Input error:', err)); gzip.on('error', (err) => console.error('Gzip error:', err)); output.on('error', (err) => console.error('Output error:', err)); input.pipe(gzip).pipe(output);
Quick Reference
| Method | Description |
|---|---|
| zlib.createGzip([options]) | Creates a gzip compression stream |
| stream.pipe(destination) | Pipes data from one stream to another |
| stream.on('error', callback) | Handles errors on streams |
| fs.createReadStream(path) | Reads data from a file as a stream |
| fs.createWriteStream(path) | Writes data to a file as a stream |
Key Takeaways
Use Node.js built-in zlib module's createGzip() to compress data streams with gzip.
Always handle errors on streams to avoid silent failures.
Pipe readable streams through gzip stream, then to writable streams for compression.
Set proper HTTP headers when sending gzip compressed responses.
Use streams for efficient compression of large files or data.