Compress a file in Node.js


Jul 27, 2020
featured image
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} 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
nodejs utils dev zip zlib