get hashes checksum from file using NodeJS
get checksum from file
const crypto = require('crypto');
const fs = require('fs');
/**
* convert file to hash
* @param {'sha1' | 'sha256' | 'sha384' | 'sha512', 'md5'} alogarithm
* @param {string} path
* @param {import('crypto').BinaryToTextEncoding} encoding
* @returns
*/
function file_to_hash(alogarithm = 'sha1', path, encoding = 'hex') {
return new Promise((resolve, reject) => {
const hash = crypto.createHash(alogarithm);
const rs = fs.createReadStream(path);
rs.on('error', reject);
rs.on('data', (chunk) => hash.update(chunk));
rs.on('end', () => resolve(hash.digest(encoding)));
});
}
Usages
file_to_hash('sha512', 'D:/Repositories/release/file.tgz').then(console.log);