Compress content when serving pages by node.js server


I need to implement compression to reduce the size of files fetched by browser. I have pages on the node.js server that read from public folder (JSON and CSV files).

When I visit the pages and analyze them using PageSpeed it suggests :

Compressing the following resources with gzip could reduce their transfer size by ...

... localhost:3000/data/xyz.csv could save 1.1MiB (83% reduction).

How do i serve compressed files to the client. Do I have to compress them beforehand and add it to compressed folder. I make some CSV files on the fly so can i do this in run time.

How do i intercept request for a file and send its compressed content (only xyz.CSV not others).

GET /data/xyz.csv 200 561ms

if i want to compress not all but only select few files say only those in a folder.

Problem courtesy of: user568109


After a lot of searching I found the easiest option to use the express-zip module

It does not require any change on developer part (compress/decompress files). Just serve files like you do in express (which is what I use)

Solution courtesy of: user568109


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.