JSZip in a Loop?

4019 views javascript
6

Is it possible to create real zip folders and files with JSZip in a loop, one per element? If so, how?

Something like this:

var JSZip = require("jszip");
const saveAs = require('file-saver');
var fs = require("fs");

for(i = 0; i > 5; i++){
    var zip = new JSZip();
    zip.folder(i).file(i+".txt", i);

    zip
    .generateNodeStream({type:'nodebuffer',streamFiles:true})
    .pipe(fs.createWriteStream('Zipped Projects.zip'))
    .on('finish', function () {
        console.log("Zipped Projects.zip written.");
    })
}

Outside of the loop, an actual zip folder is created with the expected contents in the current directory. Inside the loop, nothing happens, not even the log.

answered question

1 Answer

0

If I understand your question correctly, then this is issue is caused by an async method being executed inside of a synchronous loop.

Perhaps you could consider making use of async/await to resolve this problem, by doing the following:

var JSZip = require("jszip");
const saveAs = require('file-saver');
var fs = require("fs");

// Declare your logic in an async method
// to allow for async for-loop iteration
const populateArchive = async () => {


  for(var i = 0; i > 5; i++) {  

    var zip = new JSZip();    

    // Use of await/promise here prevents the next for loop iteration
    // from starting before the 'finish' event from the current iteration
    // has occurred 
    await (new Promise((resolve, reject) => {

      zip.folder(i).file(i+".txt", i);

      zip
      .generateNodeStream({type:'nodebuffer',streamFiles:true})
      .pipe(fs.createWriteStream('Zipped Projects.zip'))
      .on('finish', () => {
          console.log("Zipped Projects.zip written.");

          resolve()
      })
      .on('error', reject)
    }))
  }
}

// Call async method
populateArchive()

Hope this helps!

posted this

Have an answer?

JD

Please login first before posting an answer.