获取资源,计算哈希,返回承诺 [英] fetch resource, compute hash, return promise
问题描述
我想在浏览器扩展程序中使用获取API 下载资源并计算其哈希值.以下作品(通过
I would like to use the Fetch API in a browser extension to download a resource and compute a hash thereof. The following works (using crypto through Browserify)
fetch(url).then(function(response) {
return response.blob();
}).then(function(data) {
var a = new FileReader();
a.readAsBinaryString(data);
a.onloadend = function() {
var hash = crypto.createHash(hashType);
hash.update(a.result, 'binary');
return hash.digest('hex');
};
})
,但缺点是我必须等待a.onloadend
,而要嵌入它的上下文需要返回Promise
.同样,首先获取整个Blob,然后将其读取到FileReader
,然后再将其转储到createHash
,似乎很奇怪.
but has the disadvantage that I have to wait for a.onloadend
while the context in which I'd like to embed it requires a Promise
to be returned. Also, it seems quite weird to first fetch the entire blob, then read it into a FileReader
just to dump it into createHash
afterwards.
有任何提示吗?
推荐答案
密码hash.update
方法也需要一个缓冲区,因此无需通过FileReader
绕行.随便
fetch(url).then(function(response) {
return response.arrayBuffer();
}).then(function(arrayBuffer) {
var buffer = require('buffer')(new Uint8Array(arrayBuffer));
var hash = require('crypto').createHash(hashType);
hash.update(buffer, 'binary');
return hash.digest('hex');
})
如果这不起作用,则可以轻松实现 a FileReader
:
If that doesn't work, you can easily promisify a FileReader
:
function getResult(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(this.result);
};
reader.onerror = reader.onabort = reject;
});
}
并像这样使用它:
fetch(url).then(function(response) {
return response.blob();
}).then(function(data) {
var a = new FileReader();
a.readAsBinaryString(data);
return getResult(a);
}).then(function(result) {
var hash = crypto.createHash(hashType);
hash.update(result, 'binary');
return hash.digest('hex');
})
这篇关于获取资源,计算哈希,返回承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!