簡體   English   中英

如何以編程方式知道 NodeJS 應用程序何時用完 memory

[英]How to programmatically know when NodeJS application is running out of memory

我怎么知道我的應用程序何時用完 memory。

對我來說,我在服務器上進行一些視頻轉碼,有時會導致 memory 錯誤。

所以,我想知道應用程序何時用完 memory 以便我可以立即終止視頻轉碼器。

謝謝你。

您可以看到內置process模塊使用了多少 memory。

const process = require("process");

process模塊有一個名為memoryUsage的方法,它顯示 Node.js 中 memory 的使用信息。

console.log(process.memoryUsage());

運行代碼時,您應該會看到一個 object,其中包含使用 memory 所需的所有信息!

$ node index.js
{
  rss: 4935680,
  heapTotal: 1826816,
  heapUsed: 650472,
  external: 49879,
  arrayBuffers: 9386
}

以下是對每個屬性的一些見解。

  • rss -(常駐集大小)在主 memory 設備中占用的空間量。
  • heapTotal - V8 引擎中 memory 的總量。
  • heapUsed - V8 引擎使用的 memory 的數量。
  • external - C++ 對象的 memory 用法綁定到 JavaScript 對象(由 V8 管理)。
  • arrayBuffers - 分配給ArrayBufferBuffer的 memory。

對於您的問題,您可能需要使用heapTotalheapUsed 根據該值,您可以關閉該服務。 例如:

const process = require("process");

const mem = process.memoryUsage();
const MAX_SIZE = 50; // Change the value to what you want

if ((mem.heapUsed / 1000000) >= MAX_SIZE) {
  videoTranscoder.kill(); // Just an example...
}

除以一百萬部分只是將字節轉換為兆字節(B 到 MB)。

將代碼更改為您喜歡的代碼 - 這只是一個示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM