hashing.ts 796 B

123456789101112131415161718192021222324252627282930
  1. import * as multihash from 'multihashes'
  2. import fs from 'fs'
  3. import { createHash } from 'blake3'
  4. /**
  5. * Reads the file and calculates its hash. It uses the blake3 hashing algorithm
  6. * and multihash format.
  7. *
  8. * @param filename - file name
  9. * @returns hash promise.
  10. */
  11. export function hashFile(filename: string): Promise<string> {
  12. const fileStream = fs.createReadStream(filename).pipe(createHash())
  13. return new Promise((resolve, reject) => {
  14. let hash: Uint8Array
  15. fileStream.on('data', function (chunk) {
  16. hash = chunk
  17. })
  18. fileStream.on('end', function () {
  19. const encoded = multihash.encode(hash, 'blake3')
  20. const result = multihash.toB58String(encoded)
  21. resolve(result)
  22. })
  23. fileStream.on('error', function (err) {
  24. reject(err)
  25. })
  26. })
  27. }