Compress a file in Node.js

Reading Time: < 1 minutes

Compress a file in Node.js without extra dependencies.

      
   const zlib = require('zlib');
   const fs = require('fs');
   /**
     *
     * @param filePath the absolute path to the will to zip
     * @return {Promise<string>} the full absolute path to the zip file
     */
    function zip(filePath) {
        return new Promise((resolve, reject) => {
            const zipFilePath = `${filePath}.zip`;
            pipeline(
                fs.createReadStream(filePath),
                zlib.createGzip(),
                fs.createWriteStream(zipFilePath),
                (err) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(zipFilePath);
                    }
                },
            );
        });
    }
      
    

Photo by JJ Ying on Unsplash


About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: