Last updated: November 27, 2023.
You can use the JSZip library to extract file data from a zip file.
First, you need to import JSZip into your project, for example by inserting the following CDN link from cdnjs into your project before usage:
Alternatively, if you are using npm in your project, you can install using npm i jszip
.
After importing, you can extract the file data from a zip file like this:
The data is output in blob format, which contains the raw file data.
The data could also come from a HTTP request.
In the below example, data is extracted from a zip file acquired from a fetch
request:
fetch('./my_zip_file.zip')
.then(res => res.blob())
.then(data => {
extractFiles(data);
});
function extractFiles(inputFiles) {
JSZip.loadAsync(inputFiles)
.then(res => {
for (key of Object.keys(res.files)) {
res.files[key].async('blob')
.then(res => console.log(res) );
}
});
};
The nested handling of promises using .then()
can be replaced by the await
keyword by creating async functions:
async function getFile(url) {
const res = await fetch(url);
const data = await res.blob();
return data;
};
async function extractFiles(inputFiles) {
const res = await JSZip.loadAsync(inputFiles);
const filesArray = [];
for (key of Object.keys(res.files)) {
const fileData = await res.files[key].async('blob');
filesArray.push(fileData);
}
return filesArray;
};
(async () => {
const zip = await getFile('./my_zip_file.zip');
const filesArray = await extractFiles(zip);
console.log(filesArray); // Array of the files
})();
This code also has the advantage that the fetching of the file is now encapsulated in a reusable function, getFile()
.