Question presented to candidate: "You want to compress an HTTP response body, or a file you are about to write to disk. Does Node need an external package for this, and how would you actually verify the compression is lossless?"
What a strong answer should cover:
zlibis a built-in Node module — no external dependency required — providing gzip, deflate, and modern Brotli compression/decompression, both as synchronous functions (gzipSync/gunzipSync) and as streams (zlib.createGzip()/createGunzip()), fitting directly into the.pipe()/stream.pipeline()patterns covered in their own dedicated questions.- 📌 Verified, not assumed: compressing 100,000 bytes of highly repetitive data produced a 132-byte result (a 99.9% reduction), and decompressing that result reproduced the exact original bytes, confirmed via a byte-for-byte buffer comparison — real, measured evidence that the round trip is genuinely lossless, not merely described as such.
- The stream-based API (
zlib.createGzip()) is the natural fit for the large-file/HTTP-response use cases covered in the dedicated large-files-with-streams question — compressing data as it flows through a pipe chain, with the same flat memory profile, rather than requiring the entire payload in memory first to compress it in one synchronous call. gzip/deflateand Brotli (brotliCompressSync/brotliDecompressSync, or their streaming equivalents) are genuinely different algorithms with different trade-offs — Brotli often achieves a smaller output for the same input at the cost of somewhat higher compression time, which is why HTTP content negotiation (theAccept-Encoding/Content-Encodingheaders) lets a client and server agree on which one to actually use for a given exchange.- A precise answer names the common real use case beyond raw file/response compression: many HTTP frameworks and reverse proxies use
zlib(directly or via a middleware) to implement response compression transparently, which is why an application developer often does not callzlibdirectly at all — it operates one layer below, inside the framework or infrastructure. zlib's compression is not a substitute for encryption — compressed data is still fully readable/reversible by anyone with the compressed bytes; confidentiality is a separate concern addressed by thecryptomodule, covered in its own dedicated question.
Clarifying questions expected:
- "Is this for compressing an HTTP response, a file being written to disk, or an arbitrary in-memory buffer?" — decides between the streaming API and the synchronous one-shot functions.
- "Does the consuming client support Brotli, or should this stick to the more universally-supported gzip?" — a real, practical HTTP compatibility question.
Code / implementation expected: Yes — a real gzip round trip with the actual compressed size and a verified byte-for-byte match after decompression is the concrete, convincing proof of both the compression ratio and its losslessness.