Node.js Compress File into gzip Format

Node.js Node.js File System zlib

Using Node.js built-in fs and zlib modules to compress a file into gzip format.

For example, we have the Document.pdf file as below located at D:\ToriCode\Nodejs directory.

Node.js Compress File into gzip Format - Source File


Compress file using fs and zlib modules

Below Node.js code example to compress Document.pdf file above to compressed file named Document.pdf.gz

let fs = require('fs');
let zlib = require('zlib');
let gzip = zlib.createGzip();
let stream = fs.createWriteStream('Document.pdf.gz');

fs.createReadStream('Document.pdf')
    .pipe(gzip)
    .pipe(stream);

Save Node.js code above to D:\ToriCode\Nodejs\compress_file.js file and execute it.

D:\ToriCode\Nodejs> node compress_file.js

After code execution we will get the Document.pdf.gz file created in the same directory.

Node.js Compress File into gzip Format - Compressed File

Open Document.pdf.gz file with 7-Zip application.

Node.js Compress File into gzip Format