0
# Compression Operations
1
2
Compress and decompress data using various algorithms with promise support. Provides modern async/await compatibility for Node.js zlib operations.
3
4
## Capabilities
5
6
### Gzip Compression
7
8
Compress and decompress data using the gzip algorithm.
9
10
```javascript { .api }
11
/**
12
* Compress data using gzip algorithm
13
* @param buffer - Data to compress (Buffer or string)
14
* @param options - Compression options
15
* @returns Promise resolving to compressed Buffer
16
*/
17
function gzip(buffer, options): Promise<Buffer>;
18
19
/**
20
* Decompress gzip-compressed data
21
* @param buffer - Compressed data Buffer
22
* @param options - Decompression options
23
* @returns Promise resolving to decompressed Buffer
24
*/
25
function gunzip(buffer, options): Promise<Buffer>;
26
```
27
28
### Deflate Compression
29
30
Compress and decompress data using the deflate algorithm.
31
32
```javascript { .api }
33
/**
34
* Compress data using deflate algorithm
35
* @param buffer - Data to compress (Buffer or string)
36
* @param options - Compression options
37
* @returns Promise resolving to compressed Buffer
38
*/
39
function deflate(buffer, options): Promise<Buffer>;
40
41
/**
42
* Decompress deflate-compressed data
43
* @param buffer - Compressed data Buffer
44
* @param options - Decompression options
45
* @returns Promise resolving to decompressed Buffer
46
*/
47
function inflate(buffer, options): Promise<Buffer>;
48
```
49
50
### Raw Deflate Compression
51
52
Compress and decompress data using raw deflate (without headers).
53
54
```javascript { .api }
55
/**
56
* Compress data using raw deflate algorithm (no headers)
57
* @param buffer - Data to compress (Buffer or string)
58
* @param options - Compression options
59
* @returns Promise resolving to compressed Buffer
60
*/
61
function deflateRaw(buffer, options): Promise<Buffer>;
62
63
/**
64
* Decompress raw deflate-compressed data
65
* @param buffer - Compressed data Buffer
66
* @param options - Decompression options
67
* @returns Promise resolving to decompressed Buffer
68
*/
69
function inflateRaw(buffer, options): Promise<Buffer>;
70
```
71
72
### Universal Decompression
73
74
Automatically detect and decompress various compression formats.
75
76
```javascript { .api }
77
/**
78
* Decompress data, automatically detecting the compression format
79
* @param buffer - Compressed data Buffer
80
* @param options - Decompression options
81
* @returns Promise resolving to decompressed Buffer
82
*/
83
function unzip(buffer, options): Promise<Buffer>;
84
```
85
86
**Usage Examples:**
87
88
```javascript
89
const zlib = require('mz/zlib');
90
91
// Basic gzip compression and decompression
92
async function gzipExample() {
93
try {
94
const originalData = 'Hello, World! This is some text to compress.';
95
console.log('Original:', originalData);
96
console.log('Original size:', originalData.length, 'bytes');
97
98
// Compress with gzip
99
const compressed = await zlib.gzip(originalData);
100
console.log('Compressed size:', compressed.length, 'bytes');
101
console.log('Compression ratio:', (compressed.length / originalData.length * 100).toFixed(1) + '%');
102
103
// Decompress
104
const decompressed = await zlib.gunzip(compressed);
105
console.log('Decompressed:', decompressed.toString());
106
107
} catch (error) {
108
console.error('Compression failed:', error);
109
}
110
}
111
112
// Deflate compression
113
async function deflateExample() {
114
try {
115
const data = Buffer.from('This is test data for deflate compression');
116
117
// Compress with deflate
118
const compressed = await zlib.deflate(data);
119
console.log('Deflate compressed:', compressed.length, 'bytes');
120
121
// Decompress
122
const decompressed = await zlib.inflate(compressed);
123
console.log('Decompressed:', decompressed.toString());
124
125
} catch (error) {
126
console.error('Deflate operation failed:', error);
127
}
128
}
129
130
// Raw deflate (no headers)
131
async function rawDeflateExample() {
132
try {
133
const data = 'Raw deflate compression example';
134
135
const compressed = await zlib.deflateRaw(data);
136
const decompressed = await zlib.inflateRaw(compressed);
137
138
console.log('Raw deflate works:', decompressed.toString() === data);
139
140
} catch (error) {
141
console.error('Raw deflate failed:', error);
142
}
143
}
144
145
// Universal decompression
146
async function unzipExample() {
147
try {
148
// Compress with gzip first
149
const data = 'Data compressed with gzip';
150
const gzipped = await zlib.gzip(data);
151
152
// Decompress with unzip (auto-detects format)
153
const unzipped = await zlib.unzip(gzipped);
154
console.log('Unzipped:', unzipped.toString());
155
156
} catch (error) {
157
console.error('Unzip failed:', error);
158
}
159
}
160
161
// Compress large data with options
162
async function compressWithOptions() {
163
try {
164
const largeData = 'Large data string...'.repeat(1000);
165
166
// Compress with custom options
167
const compressed = await zlib.gzip(largeData, {
168
level: 9, // Maximum compression
169
chunkSize: 1024, // Chunk size for processing
170
windowBits: 15, // Window size
171
memLevel: 8, // Memory usage level
172
strategy: zlib.constants.Z_DEFAULT_STRATEGY
173
});
174
175
console.log('Highly compressed size:', compressed.length);
176
177
const decompressed = await zlib.gunzip(compressed);
178
console.log('Decompression successful:', decompressed.length === largeData.length);
179
180
} catch (error) {
181
console.error('Compression with options failed:', error);
182
}
183
}
184
185
// Callback support is still available
186
zlib.gzip('callback example', (err, compressed) => {
187
if (err) {
188
console.error('Error:', err);
189
} else {
190
console.log('Compressed with callback:', compressed.length, 'bytes');
191
}
192
});
193
194
// File compression example
195
const fs = require('mz/fs');
196
197
async function compressFile(inputPath, outputPath) {
198
try {
199
// Read file
200
const fileData = await fs.readFile(inputPath);
201
console.log('Original file size:', fileData.length, 'bytes');
202
203
// Compress
204
const compressed = await zlib.gzip(fileData);
205
console.log('Compressed size:', compressed.length, 'bytes');
206
207
// Write compressed file
208
await fs.writeFile(outputPath, compressed);
209
console.log('Compressed file saved to:', outputPath);
210
211
} catch (error) {
212
console.error('File compression failed:', error);
213
}
214
}
215
216
// Compare compression algorithms
217
async function compareAlgorithms() {
218
const testData = 'This is test data for comparing compression algorithms. '.repeat(100);
219
220
try {
221
const gzipResult = await zlib.gzip(testData);
222
const deflateResult = await zlib.deflate(testData);
223
const deflateRawResult = await zlib.deflateRaw(testData);
224
225
console.log('Original size:', testData.length);
226
console.log('Gzip size:', gzipResult.length);
227
console.log('Deflate size:', deflateResult.length);
228
console.log('Deflate raw size:', deflateRawResult.length);
229
230
} catch (error) {
231
console.error('Comparison failed:', error);
232
}
233
}
234
```
235
236
## Compression Options
237
238
All compression functions accept an options object:
239
240
```javascript { .api }
241
interface CompressionOptions {
242
/** Compression level (0-9, where 9 is best compression) */
243
level?: number;
244
/** Chunk size for processing data */
245
chunkSize?: number;
246
/** Window size (affects compression ratio and memory usage) */
247
windowBits?: number;
248
/** Memory usage level (1-9, where 9 uses most memory) */
249
memLevel?: number;
250
/** Compression strategy */
251
strategy?: number;
252
/** Dictionary for compression (advanced usage) */
253
dictionary?: Buffer;
254
/** Information about the original data */
255
info?: boolean;
256
}
257
```
258
259
## Compression Levels
260
261
- **0**: No compression (fastest)
262
- **1**: Best speed
263
- **2-8**: Balanced speed/compression
264
- **9**: Best compression (slowest)
265
- **-1**: Default compression level
266
267
## Error Handling
268
269
Compression functions will reject with errors for:
270
- Invalid input data
271
- Corrupted compressed data
272
- Invalid options
273
- Memory allocation failures
274
275
```javascript
276
const zlib = require('mz/zlib');
277
278
async function handleCompressionErrors() {
279
try {
280
// This will fail - trying to decompress non-compressed data
281
await zlib.gunzip('not compressed data');
282
} catch (error) {
283
console.error('Decompression error:', error.message);
284
// Error codes: Z_DATA_ERROR, Z_BUF_ERROR, etc.
285
}
286
287
try {
288
// This will fail - invalid compression level
289
await zlib.gzip('data', { level: 15 }); // Max level is 9
290
} catch (error) {
291
console.error('Invalid options:', error.message);
292
}
293
}
294
```
295
296
## Performance Considerations
297
298
- **Gzip**: Good compression ratio, widely supported, includes headers
299
- **Deflate**: Similar to gzip but with different headers
300
- **DeflateRaw**: No headers, slightly smaller, faster for small data
301
- **Level 1**: Fast compression, larger output
302
- **Level 9**: Slow compression, smaller output
303
- **Chunk size**: Larger chunks use more memory but may be more efficient
304
305
## Practical Use Cases
306
307
```javascript
308
// Web server response compression
309
async function compressHttpResponse(data) {
310
try {
311
return await zlib.gzip(data);
312
} catch (error) {
313
// Return uncompressed data if compression fails
314
return Buffer.from(data);
315
}
316
}
317
318
// Database storage compression
319
async function compressForStorage(jsonData) {
320
try {
321
const stringified = JSON.stringify(jsonData);
322
const compressed = await zlib.deflate(stringified);
323
return compressed;
324
} catch (error) {
325
throw new Error('Failed to compress data for storage: ' + error.message);
326
}
327
}
328
329
// Log file compression
330
async function compressLogs(logEntries) {
331
try {
332
const logText = logEntries.join('\n');
333
return await zlib.gzip(logText, { level: 9 }); // Maximum compression for logs
334
} catch (error) {
335
throw new Error('Log compression failed: ' + error.message);
336
}
337
}
338
```
339
340
## Implementation Notes
341
342
- Uses `thenify-all` to wrap native zlib methods
343
- Maintains complete compatibility with native zlib behavior
344
- Supports both promise and callback interfaces
345
- All functions work with Buffers and strings (strings are converted to Buffers)
346
- Error behavior matches native zlib module exactly
347
- Constants from native zlib module are available (e.g., `zlib.constants.Z_BEST_COMPRESSION`)