Node.js – hash.copy() Method


The Hash class is one of the many utility classes that is used for creating the hash digests of data. The hash.copy() method creates a new Hash object that will contain a deep copy of the internal state of the current hash object.

Syntax

hash.copy([options])

Parameters

  • options −This input parameter takes input to control the stream behaviour and therefore will contain the stream.tranformOptions.

Example 1

Create a file "hashCopy.js" and copy the following code snippet. After creating the file, use the command "node hashCopy.js" to run this code.

// hash.update() demo Example

// Importing the crypto module
const crypto = require('crypto');

// Defining the hash
const hash = crypto.createHash('sha256');

// Updating the hash value
hash.update('Welcome to TutorialsPoint');
// Displaying the hash value after copying
console.log("Hash is: " + hash.copy.digest('hex'));

Output

C:\home
ode>> node hashCopy.js Hash is: c1e6fe9c48a1cf16fa6928053975cf3d987619ca0992ac20861c32a9fa0d5d17

Example 2

// hash.update() demo Example

// Importing the crypto module
const crypto = require('crypto');

// Defining the hash
const hash = crypto.createHash('sha256');

// Updating the hash value
hash.update('Tutorials Point - SIMPLY LEARNING');

// Creating copies
const copy1 = hash.copy();
const copy2 = hash.copy();

// Displaying the hash value after copying
console.log("Original Hash is: " + hash.digest('hex'));
console.log("Copy1 Hash is: " + copy1.digest('hex'));
console.log("Copy2 Hash is: " + copy2.digest('hex'));

Output

C:\home
ode>> node hashCopy.js Original Hash is: 5f7a802a94340899861ac3babd895e9c7fa8240dc8f5cf87144072d456d73a05 Copy1 Hash is: 5f7a802a94340899861ac3babd895e9c7fa8240dc8f5cf87144072d456d73a05 Copy2 Hash is: 5f7a802a94340899861ac3babd895e9c7fa8240dc8f5cf87144072d456d73a05

Updated on: 16-Aug-2021

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements