Advertisement
Intermediate Node.js, Core Node.js Modules

What does the node:zlib module provide, and how would you use it to compress an HTTP response?

Short answer

zlib provides compression/decompression (gzip, deflate, Brotli) -- commonly used to compress HTTP responses reducing bandwidth, with Accept-Encoding indicating client support, though in Express this is typically handled via the compression middleware.

Save Node.js mock interview
Advertisement
AModel answer
zlib provides compression/decompression (gzip, deflate, Brotli) -- commonly used to compress HTTP responses reducing bandwidth, with Accept-Encoding indicating client support, though in Express this is typically handled via the compression middleware.
fs.createReadStream('large-file.txt').pipe(zlib.createGzip()).pipe(fs.createWriteStream('large-file.txt.gz'));

app.use(require('compression')());
Real-world example
An API serving large JSON payloads adds the compression middleware, reducing typical response sizes by 70-80% and improving load times on slower connections.
Likely follow-ups
  • How does Brotli compare to gzip in compression ratio and CPU cost?
  • When might compressing a response hurt performance, such as for already-compressed binary content?
Related topics