File size: 1,829 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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<string>}
 */
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 };