def cid_hash_file(path): h = hashlib.sha1() size = os.path.getsize(path) with open(path, 'rb') as stream: if size < 0xF000: h.update(stream.read()) else: h.update(stream.read(0x5000)) stream.seek(int(size/3)) h.update(stream.read(0x5000)) stream.seek(size-0x5000) h.update(stream.read(0x5000)) return h.hexdigest().upper() 上面的代码用 chatGPT 转换后是这样的
function cidHashFile(path) { const h = crypto.createHash('sha1'); const size = fs.statSync(path).size; const stream = fs.createReadStream(path); if (size < 0xF000) { stream.on('data', (chunk) => { h.update(chunk); }); } else { stream.on('data', (chunk) => { if (stream.bytesRead <= 0x5000) { h.update(chunk); } else if (stream.bytesRead >= Math.floor(size / 3) && stream.bytesRead < Math.floor(size / 3) + 0x5000) { h.update(chunk); } else if (stream.bytesRead >= size - 0x5000) { h.update(chunk); } }); } stream.on('end', () => { const result = h.digest('hex').toUpperCase(); console.log(result); }); stream.on('error', (err) => { console.error('File reading error:', err); }); } 试了不同文件计算出来的 hash 不一致,有没有大佬知道原因的?
