Use hash stream instead of crypto.createHash

crypto.createHash is a write stream but not a PassThrough stream!
This commit is contained in:
Girish Ramakrishnan
2025-08-13 18:38:56 +05:30
parent d875ed5cf5
commit b5c9f034ca
3 changed files with 43 additions and 2 deletions

39
src/hash-stream.js Normal file
View File

@@ -0,0 +1,39 @@
'use strict';
const crypto = require('crypto'),
stream = require('stream'),
TransformStream = stream.Transform;
class HashStream extends TransformStream {
#hasher;
#digest;
#size;
constructor() {
super();
this.#hasher = crypto.createHash('sha256');
this.#digest = null;
this.#size = 0;
}
digest() {
return this.#digest;
}
size() {
return this.#size;
}
_transform(chunk, encoding, callback) {
this.#hasher.update(chunk);
this.#size += chunk.length;
callback(null, chunk);
}
_flush(callback) {
this.#digest = this.#hasher.digest('hex');
callback(null);
}
}
exports = module.exports = HashStream;