Skip to content

Instantly share code, notes, and snippets.

@ttchengcheng
Last active October 24, 2017 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttchengcheng/05bcf8fb5196c8e7ce4be979b306ba5f to your computer and use it in GitHub Desktop.
Save ttchengcheng/05bcf8fb5196c8e7ce4be979b306ba5f to your computer and use it in GitHub Desktop.
transform(duplex) stream generates file checksum
/* usage:
* const iStream = fs.createReadStream('./oceans.mp4');
*
* const mStream = new ChecksumStream('md5');
* mStream.on('done', function(sum) {
* console.log(sum);
* })
*
* const oStream = fs.createWriteStream('o/oceans.mp4');
*
* iStream.pipe(mStream).pipe(oStream);
*/
var crypto = require('crypto')
const Stream = require('stream')
class ChecksumStream extends Stream.Transform {
constructor (algorithm, encoding) {
super()
this._hash = crypto.createHash(algorithm || 'md5')
this._hashEncoding = encoding || 'hex'
};
_transform (chunk, encoding, callback) {
this._hash.update(chunk)
callback(null, chunk)
}
_flush (callback) {
callback()
this.emit('done', this._hash.digest(this._hashEncoding))
}
}
module.exports = ChecksumStream
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment