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.
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.
listen()
to start the web server we just created with http.createServer
. At this point, we can open the web browser.pipeline()
which do the compression.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
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.