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

Viewed 1673

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

1 Answers

I first use fs.readFileSync to read the file, then I plug that Buffer (data) as the first argument to zlib.gzipSync. What comes out is also a Buffer (the compressed data); I write that 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, replacing zlib.gzipSync with zlib.gunzipSync is the only edit you'll need to make.

Related