Created
April 27, 2022 23:22
-
-
Save tatsuyasusukida/194d062a1f75b9f5cd4636c780d04bb5 to your computer and use it in GitHub Desktop.
Node.js SHA-256 hash example
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 fs = require('fs') | |
const crypto = require('crypto') | |
if (require.main === module) { | |
main() | |
} | |
async function main () { | |
try { | |
const buffer = fs.readFileSync(process.argv[1]) | |
const digestSync = sha256hashSync(buffer) | |
const stream = fs.createReadStream(process.argv[1]) | |
const digestAsync = await sha256hashAsync(stream) | |
console.log({digestSync, digestAsync}) | |
} catch (err) { | |
console.error(err) | |
} | |
} | |
function sha256hashSync (buffer) { // <1> | |
return crypto.createHash('sha256').update(buffer).digest('hex') | |
} | |
async function sha256hashAsync (stream) { // <2> | |
return await new Promise((resolve, reject) => { | |
const hash = crypto.createHash('sha256') | |
hash.once('finish', () => resolve(hash.read().toString('hex'))) | |
stream.once('error', err => reject(err)) | |
stream.pipe(hash) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment