• Node.js Video Tutorials

Node.js - os.freemem() 方法



Node.js 的os 模組提供了一組與作業系統相關的實用程式方法和屬性。本章,我們將學習os 模組的os.freemem() 方法以及相應的示例。

Node.js 的os.freemem() 方法將以整數的形式返回當前計算機 RAM 中剩餘的可用記憶體量(以位元組為單位)。此值始終小於 `totalmem` 返回的總系統記憶體量(以位元組為單位)。此返回值可用於確定程序是否需要更多記憶體,或者由於資源不足是否應縮減其操作。

語法

以下是Node.js os.freemem() 方法的語法:

os.freemem()

引數

此方法不接受任何引數。

返回值

此方法將返回以整數形式表示的可用系統記憶體量(以位元組為單位)。

以下是轉換圖表:

  • 1024 位元組 = 1KB(千位元組)

  • 1024 KB = 1 MB(兆位元組)

  • 1024 MB = 1 GB(吉位元組)

  • 1024 GB = 1 TB(太位元組)

  • 1024 TB = 1 PB(拍位元組)

示例

在下面的示例中,我們嘗試使用os.freemem() 方法列印當前系統的可用空間。

const os = require('os');
console.log(os.freemem());

輸出

130521513984

注意 - 要獲得準確的結果,最好在本地執行上述程式碼。

如果我們編譯並執行上述程式,os.freemem() 將返回當前計算機以位元組為單位的可用系統記憶體。

9211826176

示例

在下面的示例中,我們嘗試將可用系統記憶體量從位元組轉換為 KB(千位元組)、MB(兆位元組)和 GB(吉位元組)。

const os = require('os');
var mem_in_bytes = os.freemem();
var mem_in_kb = Math.floor(os.freemem()/(1024));
var mem_in_mb = Math.floor(os.freemem()/(1024*1024));
var mem_in_gb = Math.floor(os.freemem()/(1024*1024*1024));

console.log("The amount of free current system memory(in bytes): " + mem_in_bytes);
console.log("The amount of free current system memory(in KB): " + mem_in_kb); 
console.log("The amount of free current system memory(in MB): " + mem_in_mb); 
console.log("The amount of free current system memory(in GB): " + mem_in_gb);

輸出

The amount of free current system memory(in bytes): 130537541632
The amount of free current system memory(in KB): 127478068
The amount of free current system memory(in MB): 124490
The amount of free current system memory(in GB): 121

注意 - 要獲得準確的結果,最好在本地執行上述程式碼。

如果我們編譯並執行上述程式,我們將列印以位元組、千位元組 (KB)、兆位元組 (MB) 和吉位元組 (GB) 為單位的可用系統記憶體。

The amount of free current system memory(in bytes): 9202073600
The amount of free current system memory(in KB): 8986400
The amount of free current system memory(in MB): 8775
The amount of free current system memory(in GB): 8
nodejs_os_module.htm
廣告