Download zip with axios and unzip with adm-zip in memory (electron app)

10.1k views Asked by At

I need to download a file with axios and unzip it in memory in an electron app.

I read in some SO threads (e.g.), that adm-zip supports byte buffer constructor, but I can not see this in the docs. When I extract the content, it behaves like the array is empty, but it is not. It just does create a file and does not throw any errors I do not want to use request, as the api is marked deprecated. My code is this:

const axios = require("axios");
const AdmZip = require('adm-zip');
   
const url = "http://update-service.test.w3champions.com/api/maps";
const body = await axios.get(url, {
    responseType: 'arraybuffer'
});
const data = body.data;
const zip = new AdmZip(data);
zip.extractAllTo(to, true);

I feel super stupid, because I had it one time working and then changed something and now I do not seem to find the error again :/ I sadly did not commit the working state...

edit: So, we figured it out: Electron does some weird stuff that returns an Array Buffer instead of a Buffer, that adm-zip would need. As I am lazy added the package arraybuffer-to-buffer and now the code works:

const arrayBufferToBuffer = window.require('arraybuffer-to-buffer');
const url = `${this.updateUrl}api/${fileName}?ptr=${this.isTest}`;
const body = await axios.get(url, {
    responseType: 'arraybuffer'
});

const buffer = arrayBufferToBuffer(body.data);
const zip = new AdmZip(buffer);
zip.extractAllTo(to, true);
2

There are 2 answers

4
Harsh Srivastava On BEST ANSWER

check the typeof data, maybe its not buffer.

Adm implementation: https://github.com/cthackers/adm-zip/blob/master/adm-zip.js

enter image description here

15
Matus Dubrava On

It works the same with axios. The code below is a working example.

const axios = require('axios');
const AdmZip = require('adm-zip');

const f = async () => {
    const url = 'http://update-service.test.w3champions.com/api/webui';
    const body = await axios.get(url, {
        responseType: 'arraybuffer',
    });

    var zip = new AdmZip(body.data);
    var zipEntries = zip.getEntries();

    // search for "index.html" which should be there
    for (var i = 0; i < zipEntries.length; i++) {
        console.log(zip.readAsText(zipEntries[i]));
    }

    // and to extract it into current working directory
    zip.extractAllTo('.', true);
};

f();