How to add gzip compression with Node.js?

Sometimes, we want to add gzip compression with Node.js.

In this article, we’ll look at how to add gzip compression with Node.js.

How to add gzip compression with Node.js?

To add gzip compression with Node.js, we can use the built in zlib module.

For instance, we write

const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
http.createServer((request, response) => {
  const raw = fs.createReadStream('index.html');
  let acceptEncoding = request.headers['accept-encoding'];
  if (!acceptEncoding) {
    acceptEncoding = '';
  }

  if (acceptEncoding.match(/bdeflateb/)) {
    response.writeHead(200, {
      'content-encoding': 'deflate'
    });
    raw.pipe(zlib.createDeflate()).pipe(response);
  } else if (acceptEncoding.match(/bgzipb/)) {
    response.writeHead(200, {
      'content-encoding': 'gzip'
    });
    raw.pipe(zlib.createGzip()).pipe(response);
  } else {
    response.writeHead(200, {});
    raw.pipe(response);
  }
}).listen(3000);

to call createServer with a callback to create a web server.

In the callback, we call zlib.createDeflate and pipe with response to pipe the response for compress .

And we call response.writeHead with an object to set the content-encoding response header to 'gzip‘.

Then we use raw.pipe(zlib.createGzip()).pipe(response) to compress the response with gzip compression.

Conclusion

To add gzip compression with Node.js, we can use the built in zlib module.