Extract files from a zip file in JavaScript using JSZip

OpenJavaScript 0

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:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js" integrity="sha512-XMVd28F1oH/O71fzwBnV7HucLxVwtxf26XV8P4wPk26EDxuGZ91N8bsOttmnomcCD3CS5ZMRL50H0GgOHvegtg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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:

<input type="file"/>

<script>

const fileInput = document.querySelector('input[type=file]');

fileInput.addEventListener('change', (e) => {

    JSZip.loadAsync(e.target.files[0])
    .then(res => {

        const keys = Object.keys(res.files); // Gets keys of objects (on res.files) inside which file data is located
    
        for (key of keys) {
            res.files[key].async('blob') // Queries res.files by each key, calling async('blob') extracts file data
            .then(res => { 
                console.log(res); // Logs data for each file
            });

        }
    });

});

</script>

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().