Last active
October 24, 2017 08:53
-
-
Save ttchengcheng/05bcf8fb5196c8e7ce4be979b306ba5f to your computer and use it in GitHub Desktop.
transform(duplex) stream generates file checksum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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