etag-hash
Version:
Es6 class that generates ETag using the same algorithm as S3 via MD5 sum.
48 lines (47 loc) • 1.51 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHash = exports.ETagHash = void 0;
const crypto_1 = require("crypto");
class ETagHash {
partSizeInBytes;
sums;
part;
bytes;
constructor(partSizeInMb = 5) {
this.partSizeInBytes = partSizeInMb * 1024 * 1024;
this.sums = [(0, crypto_1.createHash)('md5')];
this.part = 0;
this.bytes = 0;
}
update(chunk) {
const len = chunk.length;
if (this.bytes + len < this.partSizeInBytes) {
this.sums[this.part].update(chunk);
this.bytes += len;
}
else {
const bytesNeeded = this.partSizeInBytes - this.bytes;
this.sums[this.part].update(chunk.subarray(0, bytesNeeded));
this.part++;
this.sums.push((0, crypto_1.createHash)('md5'));
this.bytes = len - bytesNeeded;
this.sums[this.part].update(chunk.subarray(bytesNeeded));
}
return this;
}
digest() {
if (!this.part) {
return this.sums[0].digest('hex');
}
const checksum = this.sums.map((s) => s.digest('hex')).join('');
const final = (0, crypto_1.createHash)('md5')
.update(Buffer.from(checksum, 'hex'))
.digest('hex');
return `${final}-${this.part + 1}`;
}
}
exports.ETagHash = ETagHash;
const createHash = (...args) => {
return new ETagHash(...args);
};
exports.createHash = createHash;