Home
Node.js
GZIP Compress Example
Updated Jan 18, 2024
Dot Net Perls
GZIP. When generating dynamic responses with a Node.js server, we often may want to compress those responses. Fortunately Node includes zlib, which includes gzip compression.
By calling the pipeline method on a read stream, we can specify a transform. We pass zlib.createGzip as the transform, and the output is then compressed.
Example. This code implements a web server, so when we run it we need to open the localhost server in a browser on port 8080. It always serves a specified file.
http.createServer
Step 1 We call listen() to start the web server we just created with http.createServer. At this point, we can open the web browser.
Step 2 We create a read stream from the file path. This is necessary for the following calls to pipeline() which do the compression.
fs createReadStream
Step 3 We access the accept-encoding header, which is how browsers tell us whether they accept compressed responses.
Step 4 We see if "gzip" occurs in the accept-encoding header, and if so, we call pipeline with zlib.createGzip to perform compression.
const zlib = require("node:zlib"); const http = require("node:http"); const fs = require("node:fs"); const stream = require("node:stream"); const filePath = "programs/example.txt"; const server = http.createServer((req, res) => { // Step 2: create a read stream for the file we want to display. const data = fs.createReadStream(filePath); // Step 3: get accept-encoding header. const acceptEncoding = req.headers["accept-encoding"]; // Step 4: pipeline the response after testing for "gzip" in accept-encoding header. if (/gzip/.test(acceptEncoding)) { // If gzip was found, use zlib.createGzip to compress the response. res.writeHead(200, { "Content-Encoding": "gzip" }); stream.pipeline(data, zlib.createGzip(), res, (err) => { if (err) { res.end(); } }); } else { // If no gzip, write the uncompressed response. res.writeHead(200, {}); stream.pipeline(data, res, (err) => { if (err) { res.end(); } }); } console.log("Wrote response"); }); // Step 1: start the server. server.listen(8080, "localhost", () => { console.log("Server started"); });
Server started Wrote response
Summary. With pipeline() and createReadStream, we use several Node.js modules together to write compressed output. This can speed up real-world use of the server as less data is transmitted.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 18, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen