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.

JavascriptCli Tooling

Code

snippet
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 request

How 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:zlib resolves 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

FAQ

Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.