🌐
Stuk
stuk.github.io › jszip › documentation › api_jszip › load_async_object.html
JSZip.loadAsync(data [, options])
var zip = new JSZip(); zip.loadAsync(data, options); Please see the documentation of loadAsync.
🌐
Stuk
stuk.github.io › jszip › documentation › api_jszip › load_async.html
loadAsync(data [, options])
// here, "bin" is zip file containing: // folder1/folder2/folder3/file1.txt zip.loadAsync(bin) .then(function (zip) { console.log(zip.files); // folder1/folder2/folder3/file1.txt }); // with createFolders: true, all folders will be created zip.loadAsync(bin, {createFolders: true}) .then(function (zip) { console.log(zip.files); // folder1/ // folder1/folder2/ // folder1/folder2/folder3/ // folder1/folder2/folder3/file1.txt }); A zip file has a flag to say if the filename and comment are encoded with UTF-8. If it’s not set, JSZip has no way to know the encoding used.
Discussions

loadAsync in JSZip is not waiting to get completed
I am using JSZip library on browser UI and having a "content" which I am passing as body for creating a zip. More on stackoverflow.com
🌐 stackoverflow.com
JSZip.loadAsync() not working in Meteor
So I'm trying to take in a zip file from the client, using a simple input tag, and I'd like for the server to open up the zip, take a look at it's contents and then put each file in a s... More on github.com
🌐 github.com
7
August 11, 2016
Having trouble understanding promises
The problem with your example is that console.log is running outside of the await so console happens before the await is finished. You can move the console inside of the await after the keys loop and you should get the result you expect. More on reddit.com
🌐 r/learnjavascript
4
2
September 13, 2021
unzip - Extracting zipped files using JSZIP in javascript - Stack Overflow
In my webpage, a user is supposed to upload a zipped file. Within the zipped file are 2 files: another zip file and a txt file. On my server, after receiving the zip, I want to unzip the zip file to More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stuk
stuk.github.io › jszip › documentation › howto › read_zip.html
How to read a file
JSZip.loadAsync(buf).then(function (zip) { return zip.file("content.txt").async("string"); }).then(function (text) { console.log(text); }); }); }); req.on("error", function(err){ // handle error }); "use strict"; var request = require('request'); var JSZip = require("jszip"); request({ method : "GET", url : "http://localhost/.../file.zip", encoding: null // <- this one is important !
🌐
Stack Overflow
stackoverflow.com › questions › 75537542 › loadasync-in-jszip-is-not-waiting-to-get-completed
loadAsync in JSZip is not waiting to get completed
The documentation of loadAsync mentions: The promise can fail if the loaded data is not valid zip data or if it uses unsupported features (multi volume, password protected, etc). Try someting like: var contentDiff: async function(content){ zip = await JSZip.loadAsync(content, {base64: true}) .catch((err) => { console.log(err); }); return zip.files; } A slightly shorter version: var contentDiff: async function(content){ return JSZip.loadAsync(content, {base64: true}) .then((zip) => zip.files) .catch((err) => { console.log(err); }); } await contentDiff(data); Share ·
🌐
Snyk
snyk.io › advisor › jszip › functions › jszip.loadasync
How to use the jszip.loadAsync function in jszip | Snyk
August 2, 2022 - async function skinType(skinPath) { if (skinPath.endsWith(".wsz")) { return FILE_TYPES.CLASSIC; } else if (skinPath.endsWith(".wal")) { return FILE_TYPES.MODERN; } const buffer = await fsPromises.readFile(skinPath); try { const zip = await JSZip.loadAsync(buffer); if (zip.file(/.*\.(wsz|wal|zip)$/i).length) { // This is a collection of skins return FILE_TYPES.PACK; } const mains = zip.file(/^(.+\/)main\.bmp$/i); return mains.length === 1 ?
🌐
Stuk
stuk.github.io › jszip › documentation › upgrade_guide.html
Upgrade Guide - JSZip
// 2.x zip.file("test.txt").asText(); // 3.x zip.file("test.txt").async("string") .then(function (content) { // use content }); // 2.x zip.generate(); // 3.x zip.generateAsync({type:"uint8array"}) .then(function (content) { // use content }); // 2.x new JSZip(data); zip.load(data); // zip.file(...) // 3.x JSZip.loadAsync(data).then(zip) {...}; zip.loadAsync(data).then(zip) {...}; // here, zip won't have (yet) the updated content // 2.x var data = zip.file("img.jpg").asBinary(); var dataURI = "data:image/jpeg;base64," + JSZip.base64.encode(data); // 3.x zip.file("img.jpg").async("base64") .then(function (data64) { var dataURI = "data:image/jpeg;base64," + data64; }); async and loadAsync use (a polyfill of) promises, you can find the documentation here and a tutorial here.
🌐
Stuk
stuk.github.io › jszip › documentation › api_jszip › generate_async.html
generateAsync(options[, onUpdate])
Note : if the entry is already compressed (coming from a compressed zip file), calling generateAsync() with a different compression level won’t update the entry. The reason is simple : JSZip doesn’t know how compressed the content was and how to match the compression level with the implementation we use.
🌐
Stuk
stuk.github.io › jszip › documentation › examples.html
How to use JSZip
If you use an AMD loader (RequireJS for example) JSZip will register itself : you just have to put the js file at the right place, or configure the loader (see here for RequireJS).
🌐
GitHub
github.com › Stuk › jszip › issues › 334
JSZip.loadAsync() not working in Meteor · Issue #334 · Stuk/jszip
August 11, 2016 - Meteor.methods({ read: function(file) { var JSZip = Meteor.npmRequire('jszip'); var entries = []; for(var i = 0; i < file.length; i++) { JSZip.loadAsync(file[i]).then(function(zip) { zip.forEach(function (relativePath, zipEntry) { entries.push(zipEntry.name); }); }); } return entries; } }); Everything I wrote is based on the examples I've seen and theoretically it should work, however in practice I get absolutely nothing.
Author   b-nugent
Find elsewhere
🌐
Tabnine
tabnine.com › home page › code › javascript › jszip
jszip.JSZip.loadAsync JavaScript and Node.js code examples | Tabnine
JSZip.loadAsync(data) .then((zip) => { let foundCsv = false zip.forEach((relPath, file) => { if (!foundCsv && relPath.endsWith('.csv')) { foundCsv = true file.async('string').then((csvString) => { return done(null, csvString, csvString.length, options) }).catch(done) } }) if (!foundCsv) { console.error('No CSV file found in ZIP archive.') return done(new Error('no CSV file found')) } }).catch(done) origin: petrbroz/forge-cli-utils ·
🌐
Reddit
reddit.com › r/learnjavascript › having trouble understanding promises
r/learnjavascript on Reddit: Having trouble understanding promises
September 13, 2021 -

I have a general idea of how promises work and understand it on simple cases but I am working on a project where its giving me a headache... My code looks like this:

export const getFilesFromZip = async (zipFile) => {
  var jsZip = JSZip();

  const files = [];

  try {
    const res = await jsZip.loadAsync(zipFile).then((zip) => {
      Object.keys(zip.files).forEach((filename) => {
        zip.files[filename].async("string").then((fileData) => {
          files.push(fileData);
          console.log(files.length);
        });
      });
    });
    console.log("I want this to be 3:", files.length);
  } catch (error) {
    throw error;
  }
};

Basically, I am passing in a .zip file to the function and trying to extract each individual file. The code is derived from here. The Zip file contains 3 files and the console prints out

I want this to be 3: 0
1
2
3

instead of

1
2
3
I want this to be 3: 3

This is where I am having trouble. I've been messing around with asyncs and awaits and tried several combinations of .then(), but I can't seem to get my log to print out the length of the files array after it is done being populated. Simple async awaits make sense to me like this which is also in my project and works as expected:

const send = async (files) => {
  let formData = new FormData();

  files.forEach((file) => {
    formData.append("files", file);
  });

  try {
    const res = await axios({
      method: "POST",
      url: baseUrl,
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    return res;
  } catch (error) {
    throw error;
  }
};

Both codes follow a similar structure. Any advice what I am misunderstanding? Thanks

Top answer
1 of 4
1
The problem with your example is that console.log is running outside of the await so console happens before the await is finished. You can move the console inside of the await after the keys loop and you should get the result you expect.
2 of 4
1
There are a couple of issues with your example. jsZip.loadAsync(zipFile).then(...) returns a promise. As you used await, the value this promise resolves to gets assigned to res. However, you're doing nothing with res, nor are you resolving the promise to anything anyway (it will be resolved to undefined - the return value of the .then callback). An async function returns a promise which resolves to the value returned by the function. You aren't returning anything in your function. Also, the whole point of await is to allow you to work sequentially, without having to nest .then calls. await effectively 'pauses' the function at that point until the promise resolves. After jsZip.loadAsync(zipFile) resolves, the callback you registered with .then will be fired, registering further callbacks to be completed asynchronously, which will populate the files array. However, the function will resume and completes executing (including the calls to console.log) before those callbacks are called, thus nothing is logged. Instead, you should use await at each point you use a method from JSZip that returns a promise. Note that you can't do this within forEach callbacks, as you can only await within the current function. Here's a refactor of your example (I haven't tested this and it may contain errors, but you might get the right idea from it) const getFilesFromZip = async (zipFile) => { const jsZip = JSZip(); const files = []; try { const zip = await jsZip.loadAsync(zipFile); for (let filename of Object.keys(zip.files)) { const data = await zip.files[filename].async("string"); files.push(data) } } catch (error) { throw error; } return files; }; This function returns a promise that will resolve to files, once it has been populated. You would then consume it like this: getFilesFromZip("test.zip").then(files => /* use files */) You could also use promise.all() which takes an array of promises and returns a promise which resolves to an array containing all of the results (again not tested): const getFilesFromZip = (zipFile) => { const jsZip = JSZip(); const zip = await jsZip.loadAsync(zipFile); const filenames = Object.keys(zip.files).map(filename => { return zip.files[filename].async("string"); }); return Promise.all(filenames) };
🌐
Stuk
stuk.github.io › jszip › documentation › api_zipobject › async.html
async(type[, onUpdate])
Note : when using type = “uint8array”, “arraybuffer” or “blob”, be sure to check if the browser supports it (you can use JSZip.support).
🌐
Stack Overflow
stackoverflow.com › questions › 74430985 › how-to-force-function-to-await-for-jszip-loadasync-function-to-execute
How to force function to await for jszip.loadAsync() function to execute?
const jszip = require('jszip') const fs = require('fs') async function Backup(path) { let files = 0 let notEmpties = 0 let size = 0 fs.readFile(path, async (err, data) => { if (err) console.log(err) await jszip.loadAsync(data).then((zip) => { zip.forEach(async (path, file) => { files++ await file.async('arraybuffer').then((data) => { if (data.byteLength > 0) { console.log(file.name, data.byteLength) notEmpties++ size += data.byteLength } }) }) }) }) return [notEmpties, files, size] }
🌐
GitHub
github.com › Stuk › jszip › issues › 379
Read zip file throwing 'Uncaught TypeError: zip.loadAsync is not a function' · Issue #379 · Stuk/jszip
November 16, 2016 - var zip = new JSZip(); zip.loadAsync(zipfile) .then(function(data){ console.log(data) }) I am using version 3.1.3 and i am not able to read from zip file using loadAsync function, when i checked the prototype object of JSZip in console, ...
Author   vmnikhil
🌐
GitHub
github.com › Stuk › jszip › issues › 753
Can file extraction work in SYNC mode, instead of async? · Issue #753 · Stuk/jszip
March 3, 2021 - The 'async' working of jszip currently prevents this and messes with the correct sequence of the code.
Author   JoeChip96
🌐
CloudDefense.ai
clouddefense.ai › code › javascript › example › jszip
Top 10 Examples of jszip code in Javascript
// 0.000001 & friends prevent divisions by 0. var promise = new JSZip.external.Promise(function (resolve, reject) { JSZipUtils.getBinaryContent("../" + chosenAnim["anim"], function (err, data) { if (err) { reject(err); } else { resolve(data); } }); }); promise.then(JSZip.loadAsync) .then(function (zip) { console.log(zip); return zip.catch.toString(); //return zip.file("anim.json").async("string"); })
🌐
Stuk
stuk.github.io › jszip › documentation › limitations.html
Limitations of JSZip
JSZip on Github · Not all features of zip files are supported. Classic zip files will work but encrypted zip, multi-volume, etc are not supported and the loadAsync() method will return a failed promise.
🌐
GitHub
github.com › Stuk › jszip › issues › 912
Large zip file breaks with loadAsync · Issue #912 · Stuk/jszip
October 30, 2023 - Tested on Chrome/Edge/Safari. Error is : DOMException: The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired. Same file works with zip.js for example, and i...
Author   velgajski1