How to Zip files using JavaScript












11















Is there a way to zip files using JavaScript?? For an example, like in Yahoo mail, when you chose to download all the attachments from an email, it gets zipped and downloaded in a single zip file. Is JavaScript capable of doing that? If so, please provide a coding example.



I found this library called jszip to do the task but it has known and unresolved issues.



Thank you.










share|improve this question























  • yahoo does it on the server.

    – Daniel A. White
    Dec 22 '11 at 19:21











  • possible duplicate of stackoverflow.com/questions/2095697/…

    – kvc
    Dec 22 '11 at 19:23











  • @kvc I saw that too but my question is to zip files. Not unzip. So thought of asking it as another post :)

    – Isuru
    Dec 22 '11 at 19:28











  • You might be able to create a windows shell javascript that does this but you cannot do this in the browser.

    – kvc
    Dec 22 '11 at 19:35
















11















Is there a way to zip files using JavaScript?? For an example, like in Yahoo mail, when you chose to download all the attachments from an email, it gets zipped and downloaded in a single zip file. Is JavaScript capable of doing that? If so, please provide a coding example.



I found this library called jszip to do the task but it has known and unresolved issues.



Thank you.










share|improve this question























  • yahoo does it on the server.

    – Daniel A. White
    Dec 22 '11 at 19:21











  • possible duplicate of stackoverflow.com/questions/2095697/…

    – kvc
    Dec 22 '11 at 19:23











  • @kvc I saw that too but my question is to zip files. Not unzip. So thought of asking it as another post :)

    – Isuru
    Dec 22 '11 at 19:28











  • You might be able to create a windows shell javascript that does this but you cannot do this in the browser.

    – kvc
    Dec 22 '11 at 19:35














11












11








11


3






Is there a way to zip files using JavaScript?? For an example, like in Yahoo mail, when you chose to download all the attachments from an email, it gets zipped and downloaded in a single zip file. Is JavaScript capable of doing that? If so, please provide a coding example.



I found this library called jszip to do the task but it has known and unresolved issues.



Thank you.










share|improve this question














Is there a way to zip files using JavaScript?? For an example, like in Yahoo mail, when you chose to download all the attachments from an email, it gets zipped and downloaded in a single zip file. Is JavaScript capable of doing that? If so, please provide a coding example.



I found this library called jszip to do the task but it has known and unresolved issues.



Thank you.







javascript zip zipfile






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 22 '11 at 19:20









IsuruIsuru

15.2k46155245




15.2k46155245













  • yahoo does it on the server.

    – Daniel A. White
    Dec 22 '11 at 19:21











  • possible duplicate of stackoverflow.com/questions/2095697/…

    – kvc
    Dec 22 '11 at 19:23











  • @kvc I saw that too but my question is to zip files. Not unzip. So thought of asking it as another post :)

    – Isuru
    Dec 22 '11 at 19:28











  • You might be able to create a windows shell javascript that does this but you cannot do this in the browser.

    – kvc
    Dec 22 '11 at 19:35



















  • yahoo does it on the server.

    – Daniel A. White
    Dec 22 '11 at 19:21











  • possible duplicate of stackoverflow.com/questions/2095697/…

    – kvc
    Dec 22 '11 at 19:23











  • @kvc I saw that too but my question is to zip files. Not unzip. So thought of asking it as another post :)

    – Isuru
    Dec 22 '11 at 19:28











  • You might be able to create a windows shell javascript that does this but you cannot do this in the browser.

    – kvc
    Dec 22 '11 at 19:35

















yahoo does it on the server.

– Daniel A. White
Dec 22 '11 at 19:21





yahoo does it on the server.

– Daniel A. White
Dec 22 '11 at 19:21













possible duplicate of stackoverflow.com/questions/2095697/…

– kvc
Dec 22 '11 at 19:23





possible duplicate of stackoverflow.com/questions/2095697/…

– kvc
Dec 22 '11 at 19:23













@kvc I saw that too but my question is to zip files. Not unzip. So thought of asking it as another post :)

– Isuru
Dec 22 '11 at 19:28





@kvc I saw that too but my question is to zip files. Not unzip. So thought of asking it as another post :)

– Isuru
Dec 22 '11 at 19:28













You might be able to create a windows shell javascript that does this but you cannot do this in the browser.

– kvc
Dec 22 '11 at 19:35





You might be able to create a windows shell javascript that does this but you cannot do this in the browser.

– kvc
Dec 22 '11 at 19:35












5 Answers
5






active

oldest

votes


















3














JSZip has been updated over the years. Now you can find it on its GitHub repo



It can be used together with FileSaver.js



You can install them using npm:



npm install jszip --save
npm install file-saver --save


And then import and use them:



import JSZip from 'jszip';
import FileSaver from 'file-saver';

let zip = new JSZip();
zip.file("idlist.txt", `PMID:29651880rnPMID:29303721`);
zip.generateAsync({type: "blob"}).then(function(content) {
FileSaver.saveAs(content, "download.zip");
});


Then you will download a zip file called download.zip, once you've extracted it, and you can find inside a file called idlist.txt, which has got two lines:



PMID:29651880
PMID:29303721


And for your reference, I tested with the following browsers, and all passed:




  • Firefox 59.0.2 (Windows 10)

  • Chrome 65.0.3325.181 (Windows 10)

  • Microsoft Edge 41.16299.371.0 (Windows 10)

  • Internet Explorer 11.0.60 (Windows 10)

  • Opera 52 (Mac OSX 10.13)

  • Safari 11 (Mac OSX 10.13)






share|improve this answer

































    1














    With the new HTML5 file APIs and the typed arrays, you can pretty much do anything you want in JavaScript. However, the browser support isn't going to be great. I'm guessing that's what you meant by "unresolved issues". I would recommend, for the time being, to do it on the server. For example, in PHP, you could use this extension.






    share|improve this answer































      0














      JavaScript is capable of doing this but not in a cross-browser fashion that you can count on.



      This can however be done easily with a server-side language. If you are used to PHP here is the documentation for PHP's ZIP functions: http://php.net/manual/en/book.zip.php






      share|improve this answer

































        0














        I'd recommend going straight to using Node's built-in library Zlib for this, which includes images; encode in base 64 using "buffers". Rather than using npm packages. Reasons being:





        • Zlib is a Node native library - has been kept up-to-date for nearly 10 years now - so the proofs there for long-term supports


        • Node allows you work with Buffers - i.e. you can convert your text string/images to the raw binary data and compress it that way with Zlib


        • Easily compress and decompress large files - leverage node streams to compress files in MBs or GBs


        The fact you are using jszip, would allow me to guess that you are using npm as well as node; assumes you have set up your environment correctly, i.e. node installed globally.




        Example: input.txt compressed to become input.txt.gz




        const zlib = require('zlib');
        const fs = require('fs');
        const gzip = zlib.createGzip();
        const input = fs.createReadStream('input.txt');
        const output = fs.createWriteStream('input.txt.gz');

        input.pipe(gzip).pipe(output);


        Step 1: So you require each of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fs module, the File System module.



        const zlib = require('zlib');
        const fs = require('fs');


        Step 2: The fs module, this allows you to create a readstream, are specifically called to read chunks of data. This will return a readstream object; readable stream



        const input = fs.createReadStream(FILE PATH HERE);



        __Note: This readstream object then gets piped again; this chaining of pipes on readsteam objects can occur endlessly, making pipes very flexible.




        ReadStream.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)


        Step 3: The readstream object, that has been piped and compressed is then converted to writestream object.



        const output = fs.createWriteStream('input.txt.gz');

        input.pipe(gzip).pipe(output); // returned filename input.txt.gz, within local directory


        So this library allows you easily enter a file path and decide where you want your compressed file to be. You can also choose to do the reverse, if need be.






        share|improve this answer


























        • Thanks for sharing. However, I guess the question sought a browser-side solution rather than a server-side's. Any idea on the browser-side? Thanks.

          – Yuci
          Apr 15 '18 at 7:44





















        0














        By using JSZIP we can generate and download zip file in JavaScript. For that you have to follow the steps below




        1. Download jszip zip file from http://github.com/Stuk/jszip/zipball/master

        2. Extract the zip and find jszip.js file inside dist folder


        3. Import jszip.js file in your html file like below



          <script type="text/javascript" src="jszip.js"></script>



        4. Add below function in your code and call it



          onClickDownload: function () {
          var zip = new JSZip();
          for (var i = 0; i < 5; i++) {
          var txt = 'hello';
          zip.file("file" + i + ".txt", txt);
          }
          zip.generateAsync({
          type: "base64"
          }).then(function(content) {
          window.location.href = "data:application/zip;base64," + content;
          });
          }


        5. You can download sample code from my git repository here (GIT link)







        share|improve this answer

























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8608724%2fhow-to-zip-files-using-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          JSZip has been updated over the years. Now you can find it on its GitHub repo



          It can be used together with FileSaver.js



          You can install them using npm:



          npm install jszip --save
          npm install file-saver --save


          And then import and use them:



          import JSZip from 'jszip';
          import FileSaver from 'file-saver';

          let zip = new JSZip();
          zip.file("idlist.txt", `PMID:29651880rnPMID:29303721`);
          zip.generateAsync({type: "blob"}).then(function(content) {
          FileSaver.saveAs(content, "download.zip");
          });


          Then you will download a zip file called download.zip, once you've extracted it, and you can find inside a file called idlist.txt, which has got two lines:



          PMID:29651880
          PMID:29303721


          And for your reference, I tested with the following browsers, and all passed:




          • Firefox 59.0.2 (Windows 10)

          • Chrome 65.0.3325.181 (Windows 10)

          • Microsoft Edge 41.16299.371.0 (Windows 10)

          • Internet Explorer 11.0.60 (Windows 10)

          • Opera 52 (Mac OSX 10.13)

          • Safari 11 (Mac OSX 10.13)






          share|improve this answer






























            3














            JSZip has been updated over the years. Now you can find it on its GitHub repo



            It can be used together with FileSaver.js



            You can install them using npm:



            npm install jszip --save
            npm install file-saver --save


            And then import and use them:



            import JSZip from 'jszip';
            import FileSaver from 'file-saver';

            let zip = new JSZip();
            zip.file("idlist.txt", `PMID:29651880rnPMID:29303721`);
            zip.generateAsync({type: "blob"}).then(function(content) {
            FileSaver.saveAs(content, "download.zip");
            });


            Then you will download a zip file called download.zip, once you've extracted it, and you can find inside a file called idlist.txt, which has got two lines:



            PMID:29651880
            PMID:29303721


            And for your reference, I tested with the following browsers, and all passed:




            • Firefox 59.0.2 (Windows 10)

            • Chrome 65.0.3325.181 (Windows 10)

            • Microsoft Edge 41.16299.371.0 (Windows 10)

            • Internet Explorer 11.0.60 (Windows 10)

            • Opera 52 (Mac OSX 10.13)

            • Safari 11 (Mac OSX 10.13)






            share|improve this answer




























              3












              3








              3







              JSZip has been updated over the years. Now you can find it on its GitHub repo



              It can be used together with FileSaver.js



              You can install them using npm:



              npm install jszip --save
              npm install file-saver --save


              And then import and use them:



              import JSZip from 'jszip';
              import FileSaver from 'file-saver';

              let zip = new JSZip();
              zip.file("idlist.txt", `PMID:29651880rnPMID:29303721`);
              zip.generateAsync({type: "blob"}).then(function(content) {
              FileSaver.saveAs(content, "download.zip");
              });


              Then you will download a zip file called download.zip, once you've extracted it, and you can find inside a file called idlist.txt, which has got two lines:



              PMID:29651880
              PMID:29303721


              And for your reference, I tested with the following browsers, and all passed:




              • Firefox 59.0.2 (Windows 10)

              • Chrome 65.0.3325.181 (Windows 10)

              • Microsoft Edge 41.16299.371.0 (Windows 10)

              • Internet Explorer 11.0.60 (Windows 10)

              • Opera 52 (Mac OSX 10.13)

              • Safari 11 (Mac OSX 10.13)






              share|improve this answer















              JSZip has been updated over the years. Now you can find it on its GitHub repo



              It can be used together with FileSaver.js



              You can install them using npm:



              npm install jszip --save
              npm install file-saver --save


              And then import and use them:



              import JSZip from 'jszip';
              import FileSaver from 'file-saver';

              let zip = new JSZip();
              zip.file("idlist.txt", `PMID:29651880rnPMID:29303721`);
              zip.generateAsync({type: "blob"}).then(function(content) {
              FileSaver.saveAs(content, "download.zip");
              });


              Then you will download a zip file called download.zip, once you've extracted it, and you can find inside a file called idlist.txt, which has got two lines:



              PMID:29651880
              PMID:29303721


              And for your reference, I tested with the following browsers, and all passed:




              • Firefox 59.0.2 (Windows 10)

              • Chrome 65.0.3325.181 (Windows 10)

              • Microsoft Edge 41.16299.371.0 (Windows 10)

              • Internet Explorer 11.0.60 (Windows 10)

              • Opera 52 (Mac OSX 10.13)

              • Safari 11 (Mac OSX 10.13)







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 15 '18 at 10:00

























              answered Apr 14 '18 at 22:57









              YuciYuci

              4,1763135




              4,1763135

























                  1














                  With the new HTML5 file APIs and the typed arrays, you can pretty much do anything you want in JavaScript. However, the browser support isn't going to be great. I'm guessing that's what you meant by "unresolved issues". I would recommend, for the time being, to do it on the server. For example, in PHP, you could use this extension.






                  share|improve this answer




























                    1














                    With the new HTML5 file APIs and the typed arrays, you can pretty much do anything you want in JavaScript. However, the browser support isn't going to be great. I'm guessing that's what you meant by "unresolved issues". I would recommend, for the time being, to do it on the server. For example, in PHP, you could use this extension.






                    share|improve this answer


























                      1












                      1








                      1







                      With the new HTML5 file APIs and the typed arrays, you can pretty much do anything you want in JavaScript. However, the browser support isn't going to be great. I'm guessing that's what you meant by "unresolved issues". I would recommend, for the time being, to do it on the server. For example, in PHP, you could use this extension.






                      share|improve this answer













                      With the new HTML5 file APIs and the typed arrays, you can pretty much do anything you want in JavaScript. However, the browser support isn't going to be great. I'm guessing that's what you meant by "unresolved issues". I would recommend, for the time being, to do it on the server. For example, in PHP, you could use this extension.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 22 '11 at 19:26









                      Alex TurpinAlex Turpin

                      33.8k1993129




                      33.8k1993129























                          0














                          JavaScript is capable of doing this but not in a cross-browser fashion that you can count on.



                          This can however be done easily with a server-side language. If you are used to PHP here is the documentation for PHP's ZIP functions: http://php.net/manual/en/book.zip.php






                          share|improve this answer






























                            0














                            JavaScript is capable of doing this but not in a cross-browser fashion that you can count on.



                            This can however be done easily with a server-side language. If you are used to PHP here is the documentation for PHP's ZIP functions: http://php.net/manual/en/book.zip.php






                            share|improve this answer




























                              0












                              0








                              0







                              JavaScript is capable of doing this but not in a cross-browser fashion that you can count on.



                              This can however be done easily with a server-side language. If you are used to PHP here is the documentation for PHP's ZIP functions: http://php.net/manual/en/book.zip.php






                              share|improve this answer















                              JavaScript is capable of doing this but not in a cross-browser fashion that you can count on.



                              This can however be done easily with a server-side language. If you are used to PHP here is the documentation for PHP's ZIP functions: http://php.net/manual/en/book.zip.php







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Dec 22 '11 at 19:27

























                              answered Dec 22 '11 at 19:21









                              JasperJasper

                              71k12134140




                              71k12134140























                                  0














                                  I'd recommend going straight to using Node's built-in library Zlib for this, which includes images; encode in base 64 using "buffers". Rather than using npm packages. Reasons being:





                                  • Zlib is a Node native library - has been kept up-to-date for nearly 10 years now - so the proofs there for long-term supports


                                  • Node allows you work with Buffers - i.e. you can convert your text string/images to the raw binary data and compress it that way with Zlib


                                  • Easily compress and decompress large files - leverage node streams to compress files in MBs or GBs


                                  The fact you are using jszip, would allow me to guess that you are using npm as well as node; assumes you have set up your environment correctly, i.e. node installed globally.




                                  Example: input.txt compressed to become input.txt.gz




                                  const zlib = require('zlib');
                                  const fs = require('fs');
                                  const gzip = zlib.createGzip();
                                  const input = fs.createReadStream('input.txt');
                                  const output = fs.createWriteStream('input.txt.gz');

                                  input.pipe(gzip).pipe(output);


                                  Step 1: So you require each of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fs module, the File System module.



                                  const zlib = require('zlib');
                                  const fs = require('fs');


                                  Step 2: The fs module, this allows you to create a readstream, are specifically called to read chunks of data. This will return a readstream object; readable stream



                                  const input = fs.createReadStream(FILE PATH HERE);



                                  __Note: This readstream object then gets piped again; this chaining of pipes on readsteam objects can occur endlessly, making pipes very flexible.




                                  ReadStream.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)


                                  Step 3: The readstream object, that has been piped and compressed is then converted to writestream object.



                                  const output = fs.createWriteStream('input.txt.gz');

                                  input.pipe(gzip).pipe(output); // returned filename input.txt.gz, within local directory


                                  So this library allows you easily enter a file path and decide where you want your compressed file to be. You can also choose to do the reverse, if need be.






                                  share|improve this answer


























                                  • Thanks for sharing. However, I guess the question sought a browser-side solution rather than a server-side's. Any idea on the browser-side? Thanks.

                                    – Yuci
                                    Apr 15 '18 at 7:44


















                                  0














                                  I'd recommend going straight to using Node's built-in library Zlib for this, which includes images; encode in base 64 using "buffers". Rather than using npm packages. Reasons being:





                                  • Zlib is a Node native library - has been kept up-to-date for nearly 10 years now - so the proofs there for long-term supports


                                  • Node allows you work with Buffers - i.e. you can convert your text string/images to the raw binary data and compress it that way with Zlib


                                  • Easily compress and decompress large files - leverage node streams to compress files in MBs or GBs


                                  The fact you are using jszip, would allow me to guess that you are using npm as well as node; assumes you have set up your environment correctly, i.e. node installed globally.




                                  Example: input.txt compressed to become input.txt.gz




                                  const zlib = require('zlib');
                                  const fs = require('fs');
                                  const gzip = zlib.createGzip();
                                  const input = fs.createReadStream('input.txt');
                                  const output = fs.createWriteStream('input.txt.gz');

                                  input.pipe(gzip).pipe(output);


                                  Step 1: So you require each of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fs module, the File System module.



                                  const zlib = require('zlib');
                                  const fs = require('fs');


                                  Step 2: The fs module, this allows you to create a readstream, are specifically called to read chunks of data. This will return a readstream object; readable stream



                                  const input = fs.createReadStream(FILE PATH HERE);



                                  __Note: This readstream object then gets piped again; this chaining of pipes on readsteam objects can occur endlessly, making pipes very flexible.




                                  ReadStream.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)


                                  Step 3: The readstream object, that has been piped and compressed is then converted to writestream object.



                                  const output = fs.createWriteStream('input.txt.gz');

                                  input.pipe(gzip).pipe(output); // returned filename input.txt.gz, within local directory


                                  So this library allows you easily enter a file path and decide where you want your compressed file to be. You can also choose to do the reverse, if need be.






                                  share|improve this answer


























                                  • Thanks for sharing. However, I guess the question sought a browser-side solution rather than a server-side's. Any idea on the browser-side? Thanks.

                                    – Yuci
                                    Apr 15 '18 at 7:44
















                                  0












                                  0








                                  0







                                  I'd recommend going straight to using Node's built-in library Zlib for this, which includes images; encode in base 64 using "buffers". Rather than using npm packages. Reasons being:





                                  • Zlib is a Node native library - has been kept up-to-date for nearly 10 years now - so the proofs there for long-term supports


                                  • Node allows you work with Buffers - i.e. you can convert your text string/images to the raw binary data and compress it that way with Zlib


                                  • Easily compress and decompress large files - leverage node streams to compress files in MBs or GBs


                                  The fact you are using jszip, would allow me to guess that you are using npm as well as node; assumes you have set up your environment correctly, i.e. node installed globally.




                                  Example: input.txt compressed to become input.txt.gz




                                  const zlib = require('zlib');
                                  const fs = require('fs');
                                  const gzip = zlib.createGzip();
                                  const input = fs.createReadStream('input.txt');
                                  const output = fs.createWriteStream('input.txt.gz');

                                  input.pipe(gzip).pipe(output);


                                  Step 1: So you require each of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fs module, the File System module.



                                  const zlib = require('zlib');
                                  const fs = require('fs');


                                  Step 2: The fs module, this allows you to create a readstream, are specifically called to read chunks of data. This will return a readstream object; readable stream



                                  const input = fs.createReadStream(FILE PATH HERE);



                                  __Note: This readstream object then gets piped again; this chaining of pipes on readsteam objects can occur endlessly, making pipes very flexible.




                                  ReadStream.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)


                                  Step 3: The readstream object, that has been piped and compressed is then converted to writestream object.



                                  const output = fs.createWriteStream('input.txt.gz');

                                  input.pipe(gzip).pipe(output); // returned filename input.txt.gz, within local directory


                                  So this library allows you easily enter a file path and decide where you want your compressed file to be. You can also choose to do the reverse, if need be.






                                  share|improve this answer















                                  I'd recommend going straight to using Node's built-in library Zlib for this, which includes images; encode in base 64 using "buffers". Rather than using npm packages. Reasons being:





                                  • Zlib is a Node native library - has been kept up-to-date for nearly 10 years now - so the proofs there for long-term supports


                                  • Node allows you work with Buffers - i.e. you can convert your text string/images to the raw binary data and compress it that way with Zlib


                                  • Easily compress and decompress large files - leverage node streams to compress files in MBs or GBs


                                  The fact you are using jszip, would allow me to guess that you are using npm as well as node; assumes you have set up your environment correctly, i.e. node installed globally.




                                  Example: input.txt compressed to become input.txt.gz




                                  const zlib = require('zlib');
                                  const fs = require('fs');
                                  const gzip = zlib.createGzip();
                                  const input = fs.createReadStream('input.txt');
                                  const output = fs.createWriteStream('input.txt.gz');

                                  input.pipe(gzip).pipe(output);


                                  Step 1: So you require each of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fs module, the File System module.



                                  const zlib = require('zlib');
                                  const fs = require('fs');


                                  Step 2: The fs module, this allows you to create a readstream, are specifically called to read chunks of data. This will return a readstream object; readable stream



                                  const input = fs.createReadStream(FILE PATH HERE);



                                  __Note: This readstream object then gets piped again; this chaining of pipes on readsteam objects can occur endlessly, making pipes very flexible.




                                  ReadStream.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)


                                  Step 3: The readstream object, that has been piped and compressed is then converted to writestream object.



                                  const output = fs.createWriteStream('input.txt.gz');

                                  input.pipe(gzip).pipe(output); // returned filename input.txt.gz, within local directory


                                  So this library allows you easily enter a file path and decide where you want your compressed file to be. You can also choose to do the reverse, if need be.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Apr 15 '18 at 1:05









                                  Stephen Rauch

                                  29.6k153657




                                  29.6k153657










                                  answered Apr 15 '18 at 0:45









                                  A. TranA. Tran

                                  4017




                                  4017













                                  • Thanks for sharing. However, I guess the question sought a browser-side solution rather than a server-side's. Any idea on the browser-side? Thanks.

                                    – Yuci
                                    Apr 15 '18 at 7:44





















                                  • Thanks for sharing. However, I guess the question sought a browser-side solution rather than a server-side's. Any idea on the browser-side? Thanks.

                                    – Yuci
                                    Apr 15 '18 at 7:44



















                                  Thanks for sharing. However, I guess the question sought a browser-side solution rather than a server-side's. Any idea on the browser-side? Thanks.

                                  – Yuci
                                  Apr 15 '18 at 7:44







                                  Thanks for sharing. However, I guess the question sought a browser-side solution rather than a server-side's. Any idea on the browser-side? Thanks.

                                  – Yuci
                                  Apr 15 '18 at 7:44













                                  0














                                  By using JSZIP we can generate and download zip file in JavaScript. For that you have to follow the steps below




                                  1. Download jszip zip file from http://github.com/Stuk/jszip/zipball/master

                                  2. Extract the zip and find jszip.js file inside dist folder


                                  3. Import jszip.js file in your html file like below



                                    <script type="text/javascript" src="jszip.js"></script>



                                  4. Add below function in your code and call it



                                    onClickDownload: function () {
                                    var zip = new JSZip();
                                    for (var i = 0; i < 5; i++) {
                                    var txt = 'hello';
                                    zip.file("file" + i + ".txt", txt);
                                    }
                                    zip.generateAsync({
                                    type: "base64"
                                    }).then(function(content) {
                                    window.location.href = "data:application/zip;base64," + content;
                                    });
                                    }


                                  5. You can download sample code from my git repository here (GIT link)







                                  share|improve this answer






























                                    0














                                    By using JSZIP we can generate and download zip file in JavaScript. For that you have to follow the steps below




                                    1. Download jszip zip file from http://github.com/Stuk/jszip/zipball/master

                                    2. Extract the zip and find jszip.js file inside dist folder


                                    3. Import jszip.js file in your html file like below



                                      <script type="text/javascript" src="jszip.js"></script>



                                    4. Add below function in your code and call it



                                      onClickDownload: function () {
                                      var zip = new JSZip();
                                      for (var i = 0; i < 5; i++) {
                                      var txt = 'hello';
                                      zip.file("file" + i + ".txt", txt);
                                      }
                                      zip.generateAsync({
                                      type: "base64"
                                      }).then(function(content) {
                                      window.location.href = "data:application/zip;base64," + content;
                                      });
                                      }


                                    5. You can download sample code from my git repository here (GIT link)







                                    share|improve this answer




























                                      0












                                      0








                                      0







                                      By using JSZIP we can generate and download zip file in JavaScript. For that you have to follow the steps below




                                      1. Download jszip zip file from http://github.com/Stuk/jszip/zipball/master

                                      2. Extract the zip and find jszip.js file inside dist folder


                                      3. Import jszip.js file in your html file like below



                                        <script type="text/javascript" src="jszip.js"></script>



                                      4. Add below function in your code and call it



                                        onClickDownload: function () {
                                        var zip = new JSZip();
                                        for (var i = 0; i < 5; i++) {
                                        var txt = 'hello';
                                        zip.file("file" + i + ".txt", txt);
                                        }
                                        zip.generateAsync({
                                        type: "base64"
                                        }).then(function(content) {
                                        window.location.href = "data:application/zip;base64," + content;
                                        });
                                        }


                                      5. You can download sample code from my git repository here (GIT link)







                                      share|improve this answer















                                      By using JSZIP we can generate and download zip file in JavaScript. For that you have to follow the steps below




                                      1. Download jszip zip file from http://github.com/Stuk/jszip/zipball/master

                                      2. Extract the zip and find jszip.js file inside dist folder


                                      3. Import jszip.js file in your html file like below



                                        <script type="text/javascript" src="jszip.js"></script>



                                      4. Add below function in your code and call it



                                        onClickDownload: function () {
                                        var zip = new JSZip();
                                        for (var i = 0; i < 5; i++) {
                                        var txt = 'hello';
                                        zip.file("file" + i + ".txt", txt);
                                        }
                                        zip.generateAsync({
                                        type: "base64"
                                        }).then(function(content) {
                                        window.location.href = "data:application/zip;base64," + content;
                                        });
                                        }


                                      5. You can download sample code from my git repository here (GIT link)








                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Oct 5 '18 at 6:30









                                      Samuel Liew

                                      45k32116152




                                      45k32116152










                                      answered Oct 5 '18 at 6:02









                                      SangeetharajSangeetharaj

                                      12




                                      12






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8608724%2fhow-to-zip-files-using-javascript%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          這個網誌中的熱門文章

                                          Academy of Television Arts & Sciences

                                          L'Équipe

                                          1995 France bombings