Skip to content

Instantly share code, notes, and snippets.

@mimshins
Last active November 17, 2025 09:01
Show Gist options
  • Select an option

  • Save mimshins/52344cc51decaad6daa486bb32b141e1 to your computer and use it in GitHub Desktop.

Select an option

Save mimshins/52344cc51decaad6daa486bb32b141e1 to your computer and use it in GitHub Desktop.
Generates the cryptographic hash (fingerprint) of a local file.
import * as crypto from "crypto";
import * as fs from "fs";
/**
* Generates the cryptographic hash (fingerprint) of a local file.
*
* @param filePath The path to the file.
* @param algorithm The hashing algorithm to use (e.g., 'sha256', 'md5').
*
* @returns A promise that resolves to the hexadecimal hash string.
*/
export const getFileHash = (
filePath: string,
algorithm: string = "sha256",
): Promise<string> => {
return new Promise((resolve, reject) => {
// Create a readable stream from the file
const stream = fs.createReadStream(filePath);
// Create the hash object
const hash = crypto.createHash(algorithm);
// Pipe the stream data to the hash object
stream.on("data", hash.update);
// Once the stream ends, finalize the hash and resolve
stream.on("end", () => {
resolve(hash.digest("hex"));
});
stream.on("error", reject);
hash.on("error", reject);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment