zlib Gzip Round Trips Text Losslessly
Compress UTF-8 text with gzipSync and restore it with gunzipSync, verifying the round trip is byte-identical and reporting the size reduction.
Code
import { gzipSync, gunzipSync } from 'node:zlib';
const report = 'request status=200 path=/api/items '.repeat(50);
const original = Buffer.from(report, 'utf8');
const compressed = gzipSync(original);
const restored = gunzipSync(compressed);
console.log('original bytes:', original.byteLength);
console.log('gzip bytes:', compressed.byteLength);
console.log('lossless:', restored.equals(original));
const words = restored.toString('utf8').split(' ').filter(Boolean);
console.log('restored words:', words.length);
console.log('sample:', words.slice(0, 4).join(' '));Output
Captured from a sandboxed run of this snippet in the build pipeline.
original bytes: 1750
gzip bytes: 71
lossless: true
restored words: 150
sample: request status=200 path=/api/items requestHow it works
The only import source is node:zlib, a Node.js built-in, exposing gzipSync, gunzipSync.
Top-level bindings report, original, compressed, restored hold the demo state — nothing sits inside a function scope.
What to watch for
node:zlibresolves inside Node.js without any package — it is a core module.
Using it
The demo output is labeled (original bytes:, gzip bytes:, lossless:), so every printed line maps back to its originating operation.
Key statements
const words = restored.toString('utf8').split(' ').filter(Boolean);
const report = 'request status=200 path=/api/items '.repeat(50);
const original = Buffer.from(report, 'utf8');
Interactive Tools for This Topic
Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- Are there third-party dependencies?
- No. The imports resolve to Node.js core modules, which the runtime provides.
Report a problem with this exampleOpens a pre-filled issue on GitHub.