Hash every file with SHA-256 and group by digest. Files in one group are byte-for-byte copies, whatever their names. On a real folder of 1,587 images (85,943,049 bytes)…

Hash every file with SHA-256 and group by digest. Files in one group are byte-for-byte copies, whatever their names. On a real folder of 1,587 images (85,943,049 bytes) we found 2 duplicate groups and 3 redundant files, which wasted 589,696 bytes. Why not compare names or sizes? Names lie. The same photo gets copied into three folders under three names. Sizes lie in the other direction: two different photos can share a byte count by chance.

A SHA-256 digest of the bytes answers one question exactly: are these two files identical? Equal digests mean equal bytes for any practical purpose. This is also the idea behind content-addressed storage, which we covered in our article on content-addressed keys for transformed images. What does the script look like? Hashing every file means reading every byte. A cheaper first pass groups files by size, because two files with different sizes cannot be identical. Then it hashes only the files that share a size.

import { createHash } from 'node:crypto'; import { readdir, readFile, stat } from 'node:fs/promises'; import { join } from 'node:path'; for await (const f of walk(root)) { const { size } = await stat(f); files++; (bySize.get(size) ?? bySize.set(size, []).get(size)).push(f); } The wasted bytes are size * (copies - 1). You keep one copy, so only the extras count. What did it find?

We ran it on this site's image folder: 7889d569b639 269098 bytes x 3 images/index/compress-image-to-1mb-result.jpg images/index/compress-image-to-a-size-sample-photo.jpg images/tools/change-image-aspect-ratio-online-original.jpg 1d1156615fb5 51500 bytes x 2 images/convert/png-converter-sample-photo.webp images/convert/png-to-webp-converter-result.webp One photo lived in three places under three names. Three more copies of nothing new is 538,196 bytes. The second group adds 51,500. Total: 589,696 bytes, about 0.7% of the folder. That is a small win on a tidy repo. On a folder that grew by copy and paste, expect more.

Does the size-first pass pay off? Only 65 of 1,587 files shared a size with another file, so only 65 were read and hashed. Hashing all 1,587 reads 85,943,049 bytes. Over five runs, hashing everything took 156, 162, 199, 324 and 545 ms in-process (median 199 ms). The size-first script took 0.07 to 0.08 s wall time per run, Node start included, in all five runs. Those two timings use different clocks, so treat them as "same order, size-first is not slower". The win grows with folder size and with slow disks.

Source disclosure

This is a source-linked briefing. Read the original report from Dev Community .