'zip and download folders to local using nodejs

How to zip and download folder from D:/downloads path. As a 1st step, I was able to create a folder inside 'downloads' with dummy content. As a next step I want to zip and download that folder.

  async downloadFolder(selectedProduct) {
    try {
      let completeZip = await this.jobService.zipBlobs(selectedProduct.path, this.role).toPromise();
     if(completeZip['status']=='success'){
      let download = await this.jobService.downloadBlobs(selectedProduct.path, this.role).toPromise();
      console.log(download)
     }
    } catch (error) {
      console.log(error);
    }
  }

API:

Once file is written , I want to zip that folder and download that folder to local but nothing happens

exports.zipBlobs = async function (req, res) {
    var userrole = req.body.userrole;
    var path = req.body.path;
    fileUploadPath="d:/downloads"; 
 blobService.listBlobsSegmentedWithPrefix(containerName, path, null, (err, data) => {
                        if (err) {
                            reject(err);
                        } else {
                            data.entries.forEach(entry => {
                                console.log(entry.name);//'155ce0e4-d763-4153-909a-407dc4e328d0/63690689-e183-46ae-abbe-bb4ba5507f1a_MULTI_0_3/output/res2/res2.fcs';
                                if (fs.existsSync(fileUploadPath)) {
                                var sourceFilePath = fileUploadPath +'/'+entry.name ;
                                if (!fs.existsSync(sourceFilePath)) {
                                    fs.mkdir(require('path').dirname(sourceFilePath), { recursive: true }, (err) => {
                                        if (err) {
                                           console.log("Failed :" + err);
                                        }
                                        else{
                                           console.log('folder created,create file');
                                           const fstream = fs.createWriteStream(sourceFilePath);
                                           fstream.write('fileContent');
                                           fstream.end();
                                           fstream.on("finish", f => {
                                               console.log('finish',f) ;                
                                           });
                                           fstream.on("error", e => {
                                              console.log('error',e);
                                           });
                                        }
                                    });
                                }else{
                                    console.log('folders already exists,create file');
                                    const fstream = fs.createWriteStream(sourceFilePath);
                                    fstream.write('fileContent');
                                    fstream.end();
                                    fstream.on("finish", f => {
                                        console.log('finish',f) ;                
                                    });
                                    fstream.on("error", e => {
                                        console.log('error',e);
                                    });
                                }
                            }else{
                                console.log('downloads folder does not exists!')
                            }
                            });
                        }
                    });
}

API to zip and download folder :

exports.downloadFolders = async function (req, res) {
    var userrole = req.body.userrole;
    var path = req.body.path;
    try {
        
const folderpath = 'D:\downloads\622b6a148a813f18b8b2de81';

  require('child_process').execSync(`zip -r archive *`, {
    cwd: folderpath
  });

  // does not create zip, neither downloads
  res.download(folderpath + '/archive.zip');
  return;
    }catch(error_1) {
        res.status(200).json({
            status: error_1
        });
        return;
    }
}


Solution 1:[1]

In Javascript strings, backslashes must be doubled:

const folderpath = 'D:\\downloads\\622b6a148a813f18b8b2de81';

Without doubling them, you effectively get

const folderpath = 'D:downloads22b6a148a813f18b8b2de81'

because '\d' === 'd' and '\6' is a non-printable character.

You can also write the result of zip to the standard output and pipe it into the response object:

res.set("Content-Disposition", "attachment;filename=archive.zip");
require("child_process").exec("zip -r - *", {
  cwd: folderpath
}).stdout.pipe(res);

Solution 2:[2]

This is something I used in one of my projects where I needed the whole directory downloaded as zip:

require the following library:

const zipdir = require('zip-dir')

Then, when you need to download the zip, call it as follows:

zipdir(
    'D:/downloads/622b6a148a813f18b8b2de81',
    { saveTo: 'D:/downloads/622b6a148a813f18b8b2de81/archive.zip' },
    (err, buffer) => {
        if (err) throw err;
        console.log('New zip file created!');
    }
);

Following is the API signature:

app.get('/api/zip', function (req, res) {
    //create new zip
    zipdir(
        'D:/downloads/622b6a148a813f18b8b2de81',
        { saveTo: 'D:/downloads/622b6a148a813f18b8b2de81/archive.zip' },
        (err, buffer) => {
            if (err) throw err;
            console.log('New zip file created!');
            res.download('D:/downloads/622b6a148a813f18b8b2de81/archive.zip');
        }
    );
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Aneesh