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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.