Skip to content

Instantly share code, notes, and snippets.

@fiveisprime
Last active August 29, 2015 14:00
Show Gist options
  • Save fiveisprime/11292913 to your computer and use it in GitHub Desktop.
Save fiveisprime/11292913 to your computer and use it in GitHub Desktop.
ShaSum transform. Generate a hash with the specified algorithm from stream data.
var Transform = require('readable-stream').Transform;
var crypto = require('crypto');
var util = require('util');
var fs = require('fs');
function ShaSum(hash) {
if (!(this instanceof Transform)) {
return new ShaSum(hash);
}
Transform.call(this, arguments);
this.digester = crypto.createHash(hash || 'sha1');
}
util.inherits(ShaSum, Transform);
ShaSum.prototype._transform = function (chunk, encoding, fn) {
this.digester.update(Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk, encoding));
fn();
};
ShaSum.prototype._flush = function (fn) {
this.push(this.digester.digest('hex'));
fn();
};
fs.createReadStream('index.js').pipe(ShaSum('sha1')).pipe(process.stdout);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment