Retrieve a resource, calculate a hash, return a promise

I would like to use the Fetch API in a browser extension to load a resource and calculate its hash. The following works (using crypto via 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'); }; }) 

but it has the disadvantage that I need to wait for a.onloadend , while the context in which I would like to embed it requires Promise return. It also seems rather strange to get the whole frame first, and then read it in FileReader , then upload it to createHash .

Any clues?

+5
source share
2 answers

The crypto hash.update method also accepts a buffer, so there is no need to do a crawl through FileReader . Just do

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

If this does not work, you can easily promise FileReader :

 function getResult(reader) { return new Promise(function(resolve, reject) { reader.onload = function() { resolve(this.result); }; reader.onerror = reader.onabort = reject; }); } 

and use it as follows:

 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'); }) 
+2
source

I think what you are asking here is a promise. You can create a promise inside the then handler and return it.

 var yaypromise = fetch(url).then(function(response) { return response.blob(); }).then(function(data) { return new Promise(function(resolve, reject){ var a = new FileReader(); a.readAsBinaryString(data); a.onloadend = function() { var hash = crypto.createHash(hashType); hash.update(a.result, 'binary'); resolve(hash.digest('hex')); }; }); }) 

And then yaypromise is probably the promise you are looking for. It will resolve with hash.digest('hex')

+2
source

Source: https://habr.com/ru/post/1236851/


All Articles