How to Download a file and compress it to zip using JavaScript

Initially, the prerequisite for downloading a simple text file in javascript requires FileSaver.js. This can be downloaded from here.

Next step would be the creation of zip file. For this we need JSZIP.

1. Download jSZip and load it in your html.

2. Here comes the core part where we initialise jSZip and download a zip file.

     var zip = new JSZip();         

    //skip this step if you don't want your files in a folder.
    var folder = zip.folder("example");
    folder.file("myfile1.txt", "HELLO WORLD IN 1ST FILE"); //requires filesaver.js
    folder.file("myfile2.txt", "HELLO WORLD IN 2ND FILE");

    // on until you have completed adding files

               .then(function(content) {
                //see FileSaver.js
                saveAs(content, "");

With the above code you can now download files into zip.