Short answer:
const crypto = require('crypto');
const buffer = crypto.createHash('md5').update(str).digest();
Long answer: you need to use NodeJS’ default crypto
module (no need for a dependency here), which contains utility function and classes. It is able to create hashes (for instance MD5 or SHA-1 hashes) for you using synchronous or asynchronous methods. A short utility function named crypto.createHash(algorithm)
is useful to create a hash with minimal coding. As the docs specifies:
The algorithm
is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256'
, 'sha512'
, etc. On recent releases of OpenSSL, openssl list-message-digest-algorithms
will display the available digest algorithms.
Now, this createHash
function returns a Hash
object, which can be used with a stream (you can feed it a file, HTTP request, etc.) or a string, as you asked. If you want to use a string, use hash.update(string)
to hash it. This method returns the hash itself, so you can chain it with .digest(encoding)
to generate a string (if encoding
is set) or a Buffer
(if it’s not). Since you asked for bytes, I believe a Buffer
is what you want (Buffer
s are Uint8Array
instances).