Search code examples
node.jszipunzipjszip

Node.js jszip library to extract


I am writing some node code, and using jszip to zip and unzip some files. I know how to zip, but cannot figure out how to unzip, or decompress. There are a couple of links on stackoverflow that do not work. Anyone has any solution? Following is what I have tried

var fs = require('fs');
var JSZip   = require('jszip');
var zipName = "C:/test.zip";
var unzip = "C:/unzip";


fs.readFile(zipName, function (err, data) {
    if (err) throw err;
    var zip = new JSZip();
    zip.folder(unzip).load(data);
});

Solution

  • JSZip has no method to write files on the disk. To do it, you need to iterate over zip.files :

    var path = require("path");
    Object.keys(zip.files).forEach(function(filename) {
      var content = zip.files[filename].asNodeBuffer();
      var dest = path.join(unzip, filename);
      fs.writeFileSync(dest, content);
    }
    

    Inside a zip file, folders are represented with a forward slash '/', I think that path.join() will create a correct path but I can't test this.