Last active
September 1, 2020 20:36
-
-
Save andyvanee/abefa1585a3d00ead7371a7b3554ba55 to your computer and use it in GitHub Desktop.
Calculate the checksum of a directory of files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from "fs" | |
import crypto from "crypto" | |
import path from "path" | |
/** | |
* Calculate the checksum of a directory of files | |
*/ | |
const dirsum = async basepath => { | |
const hash = crypto.createHash("sha1") | |
const dirOpts = { withFileTypes: true } | |
for (const f of await fs.promises.readdir(basepath, dirOpts)) { | |
const abs = path.resolve(basepath, f.name) | |
hash.update(abs) | |
try { | |
if (f.isDirectory()) { | |
hash.update(await dirsum(abs)) | |
} else { | |
hash.update(await fs.promises.readFile(abs)) | |
} | |
} catch (err) { | |
console.error(`entry not readable: ${abs}`) | |
} | |
} | |
return hash.digest("hex") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment