stream-hash.js

1.4 KB v1.0
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_crypto_1 = __importDefault(require("node:crypto"));
const node_stream_1 = require("node:stream");
/**
 * A pass-through stream that records the checksum and byte size of what flows through it on the
 * given object once the stream ends. Throws when the hash algorithm is not available. With `algo`
 * set to `false` nothing is hashed and only the size is recorded.
 */
class StreamHash extends node_stream_1.Transform {
    constructor(attachment, algo) {
        super();
        this.attachment = attachment;
        this.algo = algo === false ? false : (algo || 'md5').toLowerCase();
        this.hash = this.algo === false ? null : node_crypto_1.default.createHash(this.algo);
        this.byteCount = 0;
    }
    _transform(chunk, encoding, done) {
        this.hash?.update(chunk);
        this.byteCount += chunk.length;
        done(null, chunk);
    }
    _flush(done) {
        if (this.hash) {
            this.attachment.checksum = this.hash.digest('hex');
        }
        this.attachment.size = this.byteCount;
        done();
    }
}
exports.default = StreamHash;
module.exports = exports.default;
Object.defineProperty(module.exports, 'default', { value: exports.default, enumerable: false, writable: true, configurable: true });