Skip to content

Commit

Permalink
feat(file-io): add streamHash(), update other hashing fns
Browse files Browse the repository at this point in the history
BREAKING CHANGE: `fileHash()` now async, rename `stringHash()` => `bufferHash()`
  • Loading branch information
postspectacular committed Mar 29, 2024
1 parent 946e2db commit 64a8cad
Showing 1 changed file with 46 additions and 10 deletions.
56 changes: 46 additions & 10 deletions packages/file-io/src/hash.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { TypedArray } from "@thi.ng/api";
import type { ILogger } from "@thi.ng/logger";
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { createReadStream } from "node:fs";
import type { Readable } from "node:stream";

export type HashAlgo =
| "gost-mac"
Expand All @@ -17,26 +19,60 @@ export type HashAlgo =
| "streebog512"
| "whirlpool";

export const fileHash = (
/**
* Creates a readable stream for given file and computes its hash digest using
* {@link streamHash}.
*
* @param path
* @param logger
* @param algo
*/
export const fileHash = async (
path: string,
logger?: ILogger,
algo: HashAlgo = "sha256"
) => {
logger && logger.info("reading file:", path);
return await streamHash(createReadStream(path), logger, algo);
};

/**
* Computes hash digest from given stream using chosen hash algorithm (default:
* "sha256"). If `logger` is given, the hash will be logged too.
*
* @remarks
* Also see {@link fileHash} and {@link stringHash}.
*
* @param src
* @param logger
* @param algo
*/
export const streamHash = async (
src: Readable,
logger?: ILogger,
algo: HashAlgo = "sha256"
) => {
const sum = createHash(algo);
sum.update(readFileSync(path));
for await (let chunk of src) sum.update(chunk);
const hash = sum.digest("hex");
logger && logger.info(`${algo} hash for ${path}: ${hash}`);
logger && logger.info(`${algo} hash: ${hash}`);
return hash;
};

export const stringHash = (
src: string,
/**
* Computes hash digest from given string or buffer using chosen hash algorithm
* (default: "sha256"). If `logger` is given, the hash will be logged too.
*
* @param src
* @param logger
* @param algo
*/
export const bufferHash = (
src: TypedArray | Buffer | DataView | string,
logger?: ILogger,
algo: HashAlgo = "sha256"
) => {
const sum = createHash(algo);
sum.update(src);
const hash = sum.digest("hex");
logger && logger.info(`${algo} hash for string: ${hash}`);
const hash = createHash(algo).update(src).digest("hex");
logger && logger.info(`${algo} hash: ${hash}`);
return hash;
};

0 comments on commit 64a8cad

Please sign in to comment.