loadAsync in JSZip is not waiting to get completed
JSZip.loadAsync() not working in Meteor
Having trouble understanding promises
unzip - Extracting zipped files using JSZIP in javascript - Stack Overflow
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
This is a working version I am using:
var jsZip = require('jszip')
jsZip.loadAsync(file).then(function (zip) {
Object.keys(zip.files).forEach(function (filename) {
zip.files[filename].async('string').then(function (fileData) {
console.log(fileData) // These are your file contents
})
})
})
You can get most of the information you need from http://stuk.github.io/jszip/documentation/examples.html but it's a little hard to get in one place, you have to look around a bit.
It took a bit of digging in their documentation but they have an example that shows how to read the file contents from a ZIP.
You are getting the object that describes the ZIP contents but not the actual content. Here is an adjusted version:
var JSZip = require('JSZip');
fs.readFile(filePath, function(err, data) {
if (!err) {
var zip = new JSZip();
zip.loadAsync(data).then(function(contents) {
Object.keys(contents.files).forEach(function(filename) {
zip.file(filename).async('nodebuffer').then(function(content) {
var dest = path + filename;
fs.writeFileSync(dest, content);
});
});
});
}
});