Last active
July 18, 2022 19:19
-
-
Save monochromer/2c7b43bd5504fd93d8e8a5d74cafcab6 to your computer and use it in GitHub Desktop.
node.js hashing files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require('crypto'); | |
const fs = require('fs'); | |
/** | |
* @typedef {object} HashFileOptions | |
* @prop {string} [algorithm = 'md5'] алгоритм хеширования | |
* @prop {crypto.HexBase64Latin1Encoding} [encoding = 'hex'] предствалние конечного хеша | |
*/ | |
/** | |
* @param {fs.ReadStream} inputStream | |
* @param {HashFileOptions} [options] | |
*/ | |
async function hashFile(inputStream, options = {}) { | |
return new Promise((resolve, reject) => { | |
const { algorithm = 'md5', encoding = 'hex' } = options; | |
const hash = crypto.createHash(algorithm); | |
inputStream | |
.on('error', reject) | |
.on('data', data => hash.update(data)) | |
.on('end', () => resolve(hash.digest(encoding))) | |
}); | |
} | |
async function getHashManifest(filesList) { | |
const manifest = {}; | |
const promises = filesList.map(file => { | |
return hashFile(fs.createReadStream(file)) | |
.then(hash => manifest[file] = hash) | |
}); | |
return Promise | |
.all(promises) | |
.then(() => manifest) | |
} | |
module.exports = { | |
hashFile, | |
getHashManifest | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require('node:crypto') | |
const { pipeline } = require('node:stream/promises') | |
async function computeHash(stream, algorithm = 'md5', encoding = 'hex') { | |
const hash = crypto.createHash(algorithm) | |
await pipeline(stream, hash) | |
return hash.digest(encoding) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path'); | |
const { getHashManifest } = require('./hash-lib'); | |
const files = [ | |
path.join(__dirname, 'public', 'style.css'), | |
path.join(__dirname, 'public', 'client.js'), | |
path.join(__dirname, 'index.js'), | |
path.join(__dirname, '.env'), | |
path.join(__dirname, 'package.json'), | |
]; | |
getHashManifest(files) | |
.then(console.log) | |
.catch(console.error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment