Search code examples
javascriptnode.jsgzipzlibunzip

How to use zlib.gzipSync(buffer[, options]) for compressing files, and zlib.gunzipSync(buffer[, options]) for decompressing files?


Hi everyone

I've been going through my head about using zlib in synchronous mode, (Is important to me to be Sync mode)

I have tried and failed multiple times, the node documentation is not entirely clear and use examples are missing

What I intend to do is:

A function for compress a text file "myfile.txt" that contains some data as text as "Some text" and save it as "myfile.txt.gz"

function zip(fullPathToFile){
  const zlib= require('zlib');

  //some cool stuff...using:

  zlib.gzipSync(buffer[, options])

}

A function for unzip "myfile.txt.gz" into "myfile.txt"

function unZip(fullPathToFile){
  const zlib= require('zlib');

  //some cool stuff...using:

  zlib.gunzipSync(buffer[, options])

}

all in the same directory

any idea?

thanks for all the reading and helping time


Solution

  • I'd first use fs.readFileSync to read the file, then use its return value (a Buffer of the read file) as the first argument to zlib.gzipSync. After compressing, I'd use its return value (a Buffer of the data compressed) to write to a file, using fs.writeFileSync.

    const fs = require("fs");
    const zlib = require("zlib");
    
    function zip(path) {
        let data = fs.readFileSync(path);
        data = zlib.gzipSync(data);
        fs.writeFileSync(`${path}.gz`, data);
    }
    

    For decompression, replace zlib.gzipSync with zlib.gunzipSync.