How to do it...

  1. Create a new file named compress-site.js
  2. Include the compression NPM module. Then, initialize a new ExpressJS application:
      const express = require('express') 
      const compression = require('compression') 
      const app = express() 
  1. Include the compression middleware function. Specify the level of compression to 9 (best compression) and threshold, or minimum size in bytes that the response should have to consider compressing the response body, to 0 bytes:
      app.use(compression({ level: 9, threshold: 0 })) 
  1. Define a route method to handle GET requests for path "/" which will serve a sample HTML content that we expect to be compressed and will print the encodings that the client accepts:
      app.get('/', (request, response, next) => { 
          response.send(` 
          <!DOCTYPE html> 
          <html lang="en"> 
          <head> 
              <meta charset="utf-8"> 
              <title>WebApp powered by ExpressJS</title> 
          </head> 
          <body> 
              <section role="application"> 
                  <h1>Hello! this page is compressed!</h1> 
              </section> 
          </body> 
         </html> 
          `) 
          console.log(request.acceptsEncodings()) 
     }) 
  1. Listen on port 1337 for new connections:
      app.listen( 
          1337, 
          () => console.log('Web Server running on port 1337'), 
      ) 
  1. Save the file
  2. Open a terminal and run:
      node compress-site.js 
  1. In your browser, navigate to:
      http://localhost:1337/