我想使用 Fetch API在浏览器扩展中下载资源并计算其哈希值。以下作品(使用 crypto 到 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
中似乎很奇怪。
有什么提示吗?
最佳答案
crypto hash.update
method还需要一个缓冲区,因此无需通过 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');
})
如果这不起作用,您可以 easily promisify一个 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');
})
关于javascript - 获取资源,计算哈希值,返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926399/