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

安稳与你 提交于 2021-02-10 23:28:00

问题


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);

回答1:


check the typeof data, maybe its not buffer.

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




回答2:


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


来源:https://stackoverflow.com/questions/63291156/download-zip-with-axios-and-unzip-with-adm-zip-in-memory-electron-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!