在我的项目中,我想计算文件夹的哈希值。例如,有10个文件夹,这些文件夹有许多子文件。我知道很多方法可以获取文件的哈希值,但是否有办法获取每个文件夹的哈希值呢?
我这样做的目的是了解文件夹中的文件是否已更改。
我乐意听取建议和不同的想法,需要您的帮助。提前致谢。
我这样做的目的是了解文件夹中的文件是否已更改。
我乐意听取建议和不同的想法,需要您的帮助。提前致谢。
const fsp = require("fs/promises");
const { createHash } = require("crypto");
const path = require('path');
// -----------------------------------------------------
// Returns a buffer with a computed hash of all file's metadata:
// full path, modification time and filesize
// If you pass inputHash, it must be a Hash object from the crypto library
// and you must then call .digest() on it yourself when you're done
// If you don't pass inputHash, then one will be created automatically
// and the digest will be returned to you in a Buffer object
// -----------------------------------------------------
async function computeMetaHash(folder, inputHash = null) {
const hash = inputHash ? inputHash : createHash('sha256');
const info = await fsp.readdir(folder, { withFileTypes: true });
// construct a string from the modification date, the filename and the filesize
for (let item of info) {
const fullPath = path.join(folder, item.name);
if (item.isFile()) {
const statInfo = await fsp.stat(fullPath);
// compute hash string name:size:mtime
const fileInfo = `${fullPath}:${statInfo.size}:${statInfo.mtimeMs}`;
hash.update(fileInfo);
} else if (item.isDirectory()) {
// recursively walk sub-folders
await computeMetaHash(fullPath, hash);
}
}
// if not being called recursively, get the digest and return it as the hash result
if (!inputHash) {
return hash.digest();
}
}
computeMetaHash(__dirname).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
import { Hash, createHash } from "node:crypto";
import { readdirSync, statSync } from "node:fs";
import { join } from "node:path";
/**
* Creates hash of given files/folders. Used to conditionally deploy custom
* resources depending if source files have changed
*/
export function computeMetaHash(paths: string[], inputHash?: Hash) {
const hash = inputHash ? inputHash : createHash("sha1");
for (const path of paths) {
const statInfo = statSync(path);
if (statInfo.isDirectory()) {
const directoryEntries = readdirSync(path, { withFileTypes: true });
const fullPaths = directoryEntries.map((e) => join(path, e.name));
// recursively walk sub-folders
computeMetaHash(fullPaths, hash);
} else {
const statInfo = statSync(path);
// compute hash string name:size:mtime
const fileInfo = `${path}:${statInfo.size}:${statInfo.mtimeMs}`;
hash.update(fileInfo);
}
}
// if not being called recursively, get the digest and return it as the hash result
if (!inputHash) {
return hash.digest().toString("base64");
}
return;
}
find -type f -exec md5sum "{}" +
将会返回每个文件路径的哈希值,而find -type f -exec md5sum "{}" + | md5sum | cut -c 1-32
则会哈希整个路径。此外,如果你想要获取项目提交状态的哈希值,请获取最近的提交哈希值git rev-parse HEAD
和/或调用远程git ls-remote origin -h refs/heads/master
并将其与本地git rev-parse refs/heads/master
进行比较。 - Lawrence Cherone