| 1 | 'use strict'; |
| 2 | var fs = require('fs'); |
| 3 | var crypto = require('crypto'); |
| 4 | var isStream = require('is-stream'); |
| 5 | var Promise = require('pinkie-promise'); |
| 6 | |
| 7 | var hasha = module.exports = function (input, opts) { |
| 8 | opts = opts || {}; |
| 9 | |
| 10 | var outputEncoding = opts.encoding || 'hex'; |
| 11 | |
| 12 | if (outputEncoding === 'buffer') { |
| 13 | outputEncoding = undefined; |
| 14 | } |
| 15 | |
| 16 | var hash = crypto.createHash(opts.algorithm || 'sha512'); |
| 17 | |
| 18 | var update = function (buf) { |
| 19 | var inputEncoding = typeof buf === 'string' ? 'utf8' : undefined; |
| 20 | hash.update(buf, inputEncoding); |
| 21 | }; |
| 22 | |
| 23 | if (Array.isArray(input)) { |
| 24 | input.forEach(update); |
| 25 | } else { |
| 26 | update(input); |
| 27 | } |
| 28 | |
| 29 | return hash.digest(outputEncoding); |
| 30 | }; |
| 31 | |
| 32 | hasha.stream = function (opts) { |
| 33 | opts = opts || {}; |
| 34 | |
| 35 | var outputEncoding = opts.encoding || 'hex'; |
| 36 | |
| 37 | if (outputEncoding === 'buffer') { |
| 38 | outputEncoding = undefined; |
| 39 | } |
| 40 | |
| 41 | var stream = crypto.createHash(opts.algorithm || 'sha512'); |
| 42 | stream.setEncoding(outputEncoding); |
| 43 | return stream; |
| 44 | }; |
| 45 | |
| 46 | hasha.fromStream = function (stream, opts) { |
| 47 | if (!isStream(stream)) { |
| 48 | return Promise.reject(new TypeError('Expected a stream')); |
| 49 | } |
| 50 | |
| 51 | opts = opts || {}; |
| 52 | |
| 53 | return new Promise(function (resolve, reject) { |
| 54 | stream |
| 55 | .on('error', reject) |
| 56 | .pipe(hasha.stream(opts)) |
| 57 | .on('error', reject) |
| 58 | .on('finish', function () { |
| 59 | resolve(this.read()); |
| 60 | }); |
| 61 | }); |
| 62 | }; |
| 63 | |
| 64 | hasha.fromFile = function (fp, opts) { |
| 65 | return hasha.fromStream(fs.createReadStream(fp), opts); |
| 66 | }; |
| 67 | |
| 68 | hasha.fromFileSync = function (fp, opts) { |
| 69 | return hasha(fs.readFileSync(fp), opts); |
| 70 | }; |