Skip to content

Instantly share code, notes, and snippets.

@thehappycheese
Created September 18, 2025 08:42
Show Gist options
  • Select an option

  • Save thehappycheese/041a6beeaf296ae19407cd8a88c8844d to your computer and use it in GitHub Desktop.

Select an option

Save thehappycheese/041a6beeaf296ae19407cd8a88c8844d to your computer and use it in GitHub Desktop.
/**
* Hash a file without loading the whole thing into memory
* @param {File} file
* @param {"SHA-256"|"SHA-1"} algo
*/
export async function hash_file_in_chunks(file, algo = "SHA-256") {
const chunk_size = 1000 * 1024 * 1024; // 100MB
const count_chunks = Math.ceil(file.size / chunk_size);
const output = new ArrayBuffer(32*count_chunks);
const output_view = new Uint8Array(output);
for (
let input_offset = 0, output_offset = 0;
input_offset < file.size;
input_offset += chunk_size, output_offset+=32
) {
const chunk = file.slice(input_offset, input_offset + chunk_size);
const buffer = await chunk.arrayBuffer();
const hash_buffer = await crypto.subtle.digest(algo, buffer);
output_view.set(hash_buffer, output_offset);
}
if (count_chunks >1){
return await crypto.subtle.digest(algo, output);
}else{
return output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment