當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js crypto.secureHeapUsed()用法及代碼示例

Node.js 中的 crypto.secureHeapUsed() 方法用於獲取正在運行的 Node.js 進程的安全堆使用的內存量。安全堆是為 Node.js 進程中的加密操作保留的內存部分。該內存與主堆分開,用於進程中的通用內存分配。

用法:

crypto.secureHeapUsed()

Parameters: 該方法不帶任何參數

返回值:此方法返回一個對象,指示加密模塊使用的安全內存量(以字節為單位)。

使用crypto.secureHeapUsed()方法的步驟:

步驟1:為了使用加密.secureHeapUsed(),您需要使用以下語句在 Node.js 應用程序中導入 crypto 模塊。

const crypto = require('crypto');

第 2 步:執行一些加密操作,讓我們生成一個隨機 key 並計算哈希值:

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

步驟3:現在調用crypto.secureHeapUsed()方法來獲取安全堆使用的內存量:

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

示例 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}`);

輸出:

Secure heap used: 16384

示例 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);

輸出:

Bytes used: 12288

輸出將根據平台和分配給安全堆的內存量而有所不同。

參考: https://nodejs.org/api/crypto.html#cryptosecureheapused



相關用法


注:本文由純淨天空篩選整理自pulamolusaimohan大神的英文原創作品 Node.js crypto.secureHeapUsed() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。