const crypto = require("node:crypto"); const fs = require("node:fs"); /** * Generate a secure, fast hash of a file by taking chunks of it (sample based) * @param {string} filePath * @returns {Promise} */ function calculateFileHash(filePath) { return new Promise((resolve, reject) => { try { if (!fs.existsSync(filePath)) { return reject(new Error(`File not found: ${filePath}`)); } const stat = fs.statSync(filePath); const size = stat.size; if (size === 0) { return reject(new Error('File is empty')); } const sampleSize = 1024 * 1024; // 1MB sample const hash = crypto.createHash('sha256'); // For files smaller than 2MB, hash the whole file if (size <= sampleSize * 2) { const stream = fs.createReadStream(filePath); stream.on('data', chunk => hash.update(chunk)); stream.on('end', () => resolve(`${size}_${hash.digest('hex')}`)); stream.on('error', err => reject(err)); return; } // For large files, sample beginning, middle, and end to keep hashing ultra fast (<100ms) const fd = fs.openSync(filePath, 'r'); const buffer = Buffer.alloc(sampleSize); // 1. Read beginning fs.readSync(fd, buffer, 0, sampleSize, 0); hash.update(buffer); // 2. Read middle const middlePos = Math.floor(size / 2) - Math.floor(sampleSize / 2); fs.readSync(fd, buffer, 0, sampleSize, middlePos); hash.update(buffer); // 3. Read end const endPos = size - sampleSize; fs.readSync(fd, buffer, 0, sampleSize, endPos); hash.update(buffer); fs.closeSync(fd); resolve(`${size}_${hash.digest('hex')}`); } catch (err) { reject(err); } }); } module.exports = { calculateFileHash };