Open In App

Node.js crypto.secureHeapUsed() Method

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The crypto.secureHeapUsed() method in Node.js is used to get the amount of memory used by the secure heap of the running Node.js process. The secure heap is a section of memory that is reserved for cryptographic operations in the Node.js process. This memory is separate from the main heap, which is used for general-purpose memory allocation in the process.

Syntax:

crypto.secureHeapUsed()

Parameters: This method does not take any parameters

Return Value: This method returns an object indicating the amount of secure memory used by the crypto module, in bytes. 

Steps to use crypto.secureHeapUsed() method:

Step 1: In order to use crypto.secureHeapUsed(), you need to import the crypto module in your Node.js application using the following statement.

const crypto = require('crypto');

Step 2: Perform some cryptographic operations, Let’s generate a random key and compute a hash:

const key = crypto.randomBytes(32);
const hash = crypto.createHash('sha256')
    .update('GeeksForGeeks').digest('hex');

Step 3: Now call the crypto.secureHeapUsed() method to get the amount of memory used by the secure heap:

const bytesUsed = crypto.secureHeapUsed();
console.log(`Heap used by this process: ${bytesUsed} bytes`);

Example 1:

Javascript




const crypto = require('crypto');
 
// Perform some cryptographic operations
const key = crypto.randomBytes(256);
const hash = crypto.createHash('sha256')
    .update('GeeksForGeeks').digest('hex');
 
// Get the amount of memory used by the secure heap
const bytesUsed = crypto.secureHeapUsed();
 
console.log(`Secure heap used: ${bytesUsed.used}`);


Output:

Secure heap used: 16384

Example 2:

Javascript




const crypto = require('crypto');
 
function generateRandomNumbers(num) {
    const rand = crypto.randomBytes(num);
 
    // Calculating the secure heap used after
    // doing the cryptographic operation
    console.log(`Bytes used:
        ${crypto.secureHeapUsed().used} bytes`);
}
 
// Making a function call to
// generate 64 random bytes
generateRandomNumbers(64);


Output:

Bytes used: 12288

The output will be varied depending on the platform and the amount of memory allocated to the secure heap.

Reference: https://nodejs.org/api/crypto.html#cryptosecureheapused



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads