UNPKG

2.66 kBJavaScriptView Raw
1import { Md5 } from './md5';
2// Hashes any blob
3export class Md5FileHasher {
4 constructor(_callback, // Callback to return the result
5 _async = true, // Async version is not always available in a web worker
6 _partSize = 1048576) {
7 this._callback = _callback;
8 this._async = _async;
9 this._partSize = _partSize;
10 this._configureReader();
11 }
12 /**
13 * Hash a blob of data in the worker
14 * @param blob Data to hash
15 */
16 hash(blob) {
17 const self = this;
18 self._blob = blob;
19 // self._length = Math.ceil(blob.size / self._partSize);
20 self._part = 0;
21 self._md5 = new Md5();
22 self._processPart();
23 }
24 _fail() {
25 this._callback({
26 success: false,
27 result: 'data read failed'
28 });
29 }
30 _hashData(e) {
31 let self = this;
32 self._md5.appendByteArray(new Uint8Array(e.target.result));
33 if (self._part * self._partSize >= self._blob.size) {
34 self._callback({
35 success: true,
36 result: self._md5.end()
37 });
38 }
39 else {
40 self._processPart();
41 }
42 }
43 _processPart() {
44 const self = this;
45 let endbyte = 0;
46 let current_part;
47 self._part += 1;
48 if (self._blob.size > self._partSize) { // If blob bigger then part_size we will slice it up
49 endbyte = self._part * self._partSize;
50 if (endbyte > self._blob.size) {
51 endbyte = self._blob.size;
52 }
53 current_part = self._blob.slice((self._part - 1) * self._partSize, endbyte);
54 }
55 else {
56 current_part = self._blob;
57 }
58 if (self._async) {
59 self._reader.readAsArrayBuffer(current_part);
60 }
61 else {
62 setTimeout(() => {
63 try {
64 self._hashData({
65 target: {
66 result: self._reader.readAsArrayBuffer(current_part)
67 },
68 });
69 }
70 catch (e) {
71 self._fail();
72 }
73 }, 0);
74 }
75 }
76 _configureReader() {
77 const self = this;
78 if (self._async) {
79 self._reader = new FileReader();
80 self._reader.onload = self._hashData.bind(self);
81 self._reader.onerror = self._fail.bind(self);
82 self._reader.onabort = self._fail.bind(self);
83 }
84 else {
85 self._reader = new FileReaderSync();
86 }
87 }
88}
89//# sourceMappingURL=md5_file_hasher.js.map
\No newline at end of file