[英]Download zip with axios and unzip with adm-zip in memory (electron app)
I need to download a file with axios
and unzip it in memory in an electron app.我需要下载一个带有
axios
的文件并将其解压缩到 electron 应用程序中的 memory 中。
I read in some SO threads ( eg ), that adm-zip
supports byte buffer constructor, but I can not see this in the docs.我在一些 SO 线程( 例如)中读到,
adm-zip
支持字节缓冲区构造函数,但我在文档中看不到这一点。 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.它只是创建一个文件并且不会抛出任何我不想使用
request
的错误,因为 api 被标记为已弃用。 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...我觉得超级愚蠢,因为我有一次工作,然后改变了一些东西,现在我似乎没有再次发现错误:/遗憾的是我没有提交工作 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.编辑:所以,我们想通了:Electron 做了一些奇怪的事情,返回一个数组缓冲区而不是一个缓冲区,这是 adm-zip 需要的。 As I am lazy added the package
arraybuffer-to-buffer
and now the code works:由于我很懒,添加了 package
arraybuffer-to-buffer
,现在代码可以工作了:
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);
It works the same with axios
.它与
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();
check the typeof data, maybe its not buffer.检查数据类型,可能不是缓冲区。
Adm implementation: https://github.com/cthackers/adm-zip/blob/master/adm-zip.js Adm 实现: https://github.com/cthackers/adm-zip/blob/master/adm-zip.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.