Node.js › Core Node.js Modules

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

Intermediate

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.

Common 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?