How to Zip files using JavaScript?

Solution 1:

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';

const zip = new JSZip();
zip.file('idlist.txt', 'PMID:29651880\r\nPMID: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)

Solution 2:

If you don't care about IE, client-zip is much faster and smaller than JSZip and is meant to solve exactly this problem (yes, this is a shameless but completely relevant plug for my library 😉).

You would do something like this (where files could be an array of fetch Responses for example, though there are many supported inputs):

import { downloadZip } from "client-zip/index.js"
import FileSaver from "file-saver"

const content = await downloadZip(files).blob()
FileSaver.saveAs(content, "download.zip");

Essentially the same usage as in Yuci's answer but updated for 2020.