diff --git a/README.md b/README.md index b536f549..6e49989a 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ hash('123456'); ``` ### HashStream() +**\[deprecated\]** use `createSha1Hash()`. Generates SHA1 hash with a transform stream. @@ -80,6 +81,18 @@ fs.createReadStream('/path/to/file') }); ``` +### createSha1Hash() +return SHA1 hash object. + This is the same as calling `createHash('utf8')` in the node.js native module crypto. + ``` js +const sha1 = createSha1Hash(); + fs.createReadStream('/path/to/file') + .pipe(sha1) + .on('finish', () => { + console.log(sha1.read()); + }); +``` + ### highlight(str, [options]) Syntax highlighting for a code block. diff --git a/lib/hash.js b/lib/hash.js index 3112a588..57a1547e 100644 --- a/lib/hash.js +++ b/lib/hash.js @@ -5,10 +5,17 @@ const crypto = require('crypto'); const ALGORITHM = 'sha1'; +function createSha1Hash() { + return crypto.createHash(ALGORITHM); +} + +/** + * @deprecated + * createHash() is stream class. + */ function HashStream() { Transform.call(this); - - this._hash = crypto.createHash(ALGORITHM); + this._hash = createSha1Hash(); } require('util').inherits(HashStream, Transform); @@ -24,9 +31,10 @@ HashStream.prototype._flush = function(callback) { }; exports.hash = content => { - const hash = crypto.createHash(ALGORITHM); + const hash = createSha1Hash(); hash.update(content); return hash.digest(); }; exports.HashStream = HashStream; +exports.createSha1Hash = createSha1Hash; diff --git a/test/scripts/hash.js b/test/scripts/hash.js index b7b2e868..820eb254 100644 --- a/test/scripts/hash.js +++ b/test/scripts/hash.js @@ -27,4 +27,23 @@ describe('hash', () => { stream.read().should.eql(sha1(content)); }); + + it('createSha1Hash', function() { + var _sha1 = hash.createSha1Hash(); + var content = '123456'; + _sha1.update(content); + _sha1.digest().should.eql(sha1(content)); + }); + + it('createSha1Hash - streamMode', function() { + var content1 = '123456'; + var content2 = '654321'; + var stream = hash.createSha1Hash(); + // explicit convert + stream.write(Buffer.from(content1)); + // implicit convert + stream.write(content2); + stream.end(); + stream.read().should.eql(sha1(content1 + content2)); + }); });