Search code examples
node.jsaws-lambdapako

How to gzip a directory/folder using pako module in Nodejs?


I am trying to gzip my folder with the help of Pako library. I couldn't found any related content about it. Can someone explain me how to use pako to gzip directory. I am using it in my lambda function along with EFS.

    let bundle = fs.readdirSync(tempDir);
    let zippedFile = pako.gzip(bundle);

My folder location looks like this data/temp/

Error

TypeError: strm.input.subarray is not a function

Solution

  • You can use fs.readdirSync() to list files in the directory, then check the stat of each file before compressing it using fs.lstatSync(). I have tested this locally on my mac.

    Then you can write the compressed file to your file system.

    const fs = require('fs');
    const pako = require('pako');
    let files = fs.readdirSync('/tmp/');
    let fileContent = '';
    files.forEach(file => {
        let path = '/tmp/' + file;
        let stats = fs.lstatSync(path);
        if (stats.isFile()) {
            let data = fs.readFileSync(path);
            fileContent += data;
        }
    });
    let zippedFile = pako.gzip(fileContent);
    const stream = fs.createWriteStream('/tmp/dir.gz');
    stream.write(zippedFile);
    stream.end();