Node.js hmac.update() Method
The hmac.update() method is an inbuilt method of class HMAC within the crypto module which is used to update the data of hmac object.
Syntax:
hmac.update(data[, inputEncoding])
Parameters: This method takes the following two parameters:
- data: It can be of string, Buffer, TypedArray, or DataView type. It is the data that is passed to this function.
- inputEncoding: It is an optional parameter. It is the encoding of the data string.
Return Value: This method does not return nothing.
Project Setup: Create a new NodeJS project and name it hmac.
mkdir hmac && cd hmac npm init -y
Now create a .js file in your project root directory and name it index.js
Example 1:
index.js
// Node.js program to demonstrate the// crypto hmac.update() method // Importing crypto moduleconst { createHmac } = require('crypto') // Creating and initializing algorithm and passwordconst algo = 'sha256'const secret = 'GFG Secret Key' // Create an HMAC instanceconst hmac = createHmac(algo, secret) // Update the internal state of the hmac objecthmac.update('GeeksForGeeks') // Perform the final operations// Return calculated hashconst result = hmac.digest('base64') // Print the resultconsole.log(`HMAC hash: ${result}`) |
Run the index.js file using the following command:
node index.js
Output:
HMAC hash: yK4+CYVa56w0Ba1g2TdY7cDM68HPXFKb+10FhnRpXFM=
Example 2:
index.js
// Node.js program to demonstrate the // crypto hmac.update() method // Defining myfileconst myfile = process.argv[2]; // Includes crypto and fs moduleconst crypto = require('crypto');const fs = require('fs'); // Creating and initializing algorithm and passwordconst algo = 'sha256'const secret = 'GFG Secret Key' // Creating Hmacconst hmac = crypto.createHmac(algo, secret); // Creating read streamconst readfile = fs.createReadStream(myfile); readfile.on('readable', () => { // Calling read method to read data const data = readfile.read(); if (data) // Updating hmac.update(data); else { // Perform the final operations // Return hash value const result = hmac.digest('hex') // Display result console.log(`HMAC hash value of ${myfile}: ${result}`); }}); |
Run the index.js file using the following command:
node index.js package.json
Output:
HMAC hash value of package.json: 38f0f975f8964343c24da940188eaeb6bb20842e3c5bf03ccb66773e98beeb73
Reference: https://nodejs.org/api/crypto.html#crypto_hmac_update_data_inputencoding


