index.js 1.4 KB

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