getFileFingerprint
type: function
since: v2.8.2
since: v2.8.2
The getFileFingerprint function generates a fingerprint for a file by hashing:
- A sample from the beginning of the file.
- Identity data (default file metadata or custom identity data).
It is useful for fast file change detection and deduplication workflows where reading the full file every time is unnecessary.
Usage
import { getFileFingerprint } from '@mustib/utils/node';
const result = await getFileFingerprint({ filePath: '/absolute/path/to/file.txt',});
if (result.status === 'success') { console.log(result.data.fingerprint);} else { console.error(result.data.message, result.data.context);}Usage with custom identity data
import { getFileFingerprint } from '@mustib/utils/node';
const result = await getFileFingerprint({ filePath: '/absolute/path/to/file.txt', hashAlgorithm: 'sha256', sampleSize: 1024, identityData: ({ stats }) => ({ size: stats.size, createdAt: stats.birthtimeMs, }),});Definition
function getFileFingerprint(options: { filePath: string; hashAlgorithm?: string; sampleSize?: number; identityData?: object | ((data: { stats: Stats }) => object);}): Promise<{ status: 'success'; data: { fingerprint: string; };} | { status: 'error'; data: { message: string; context: unknown; };}> { }Parameters
-
optionstype options = {filePath: string,hashAlgorithm?: string,sampleSize?: number,identityData?: object | ((data: { stats: Stats }) => object),};options.filePath- Absolute path to the target file.
- This field is required.
options.hashAlgorithm- Hash algorithm used by Node.js crypto (for example: `md5`, `sha256`).
- default: 'md5'
- If an invalid algorithm is provided, the function rejects.
options.sampleSize- Number used as stream end index for the content sample.
- default: 65535
- Because Node read streams use an inclusive `end`, the sampled bytes are effectively up to `sampleSize + 1` when the file is large enough.
options.identityData- Optional identity data appended to the hash input.
- Can be a static object or a callback receiving `{ stats }`.
- When omitted, it uses `{ size: stats.size, mtime: stats.mtimeMs }`.
Returns
type T = Promise<FileFingerprintSuccessResult | FileFingerprintErrorResult>;- Success result:
status: 'success'data.fingerprint: hexadecimal hash string.
- Error result:
status: 'error'data.message: descriptive error message.data.context: additional context such asfilePathand underlying error object.
- If file stat fails (for example, path does not exist), the function rejects with the underlying Node error.
Error behavior
- Returns
{ status: 'error' }with message"not a file"when the path exists but is not a file (for example, a directory). - Returns
{ status: 'error' }with message"failed to read file sample"when stream reading fails. - Rejects if
stat(filePath)fails. - Rejects if
hashAlgorithmis invalid.