Skip to content

Instantly share code, notes, and snippets.

@neharkarvishal
Created August 11, 2022 06:22
Show Gist options
  • Save neharkarvishal/0c5ef732ff16eef6c7e0d5cc37212059 to your computer and use it in GitHub Desktop.
Save neharkarvishal/0c5ef732ff16eef6c7e0d5cc37212059 to your computer and use it in GitHub Desktop.
Calculate SHA-256 hash (Node.js)
/**
* Creates a hash for a value using the SHA-256 algorithm. Returns a promise.
*
* Use crypto.createHash() to create a Hash object with the appropriate
* algorithm.
*
* Use hash.update() to add the data from val to the Hash, hash.digest() to
* calculate the digest of the data.
*
* Use setTimeout() to prevent blocking on a long operation. Return a Promise to
* give it a familiar interface.
*
*/
const crypto = require('crypto')
const hashNode = val =>
new Promise(resolve =>
setTimeout(
() => resolve(crypto.createHash('sha256').update(val).digest('hex')),
0
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment