简体   繁体   English

如何以编程方式知道 NodeJS 应用程序何时用完 memory

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

How can I know when my application is running out of memory.我怎么知道我的应用程序何时用完 memory。

For me, I'm doing some video transcoding on the server and sometimes it leads to out of memory errors.对我来说,我在服务器上进行一些视频转码,有时会导致 memory 错误。

So, I wish to know when the application is running out of memory so I can immediately kill the Video Transcoder.所以,我想知道应用程序何时用完 memory 以便我可以立即终止视频转码器。

Thank you.谢谢你。

You can see how much memory is being used with the built-in process module.您可以看到内置process模块使用了多少 memory。

const process = require("process");

The process module has a method calledmemoryUsage , which shows info on the memory usage in Node.js. process模块有一个名为memoryUsage的方法,它显示 Node.js 中 memory 的使用信息。

console.log(process.memoryUsage());

When you run the code, you should see an object with all of the information needed for memory usage!运行代码时,您应该会看到一个 object,其中包含使用 memory 所需的所有信息!

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

Here is some insight on each property.以下是对每个属性的一些见解。

  • rss - (Resident Set Size) Amount of space occupied in the main memory device. rss -(常驻集大小)在主 memory 设备中占用的空间量。
  • heapTotal - The total amount of memory in the V8 engine. heapTotal - V8 引擎中 memory 的总量。
  • heapUsed - The amount of memory used by the V8 engine. heapUsed - V8 引擎使用的 memory 的数量。
  • external - The memory usage of C++ objects bound to JavaScript objects (managed by V8). external - C++ 对象的 memory 用法绑定到 JavaScript 对象(由 V8 管理)。
  • arrayBuffers - The memory allocated for ArrayBuffer s and Buffer s. arrayBuffers - 分配给ArrayBufferBuffer的 memory。

For your question, you might need to use heapTotal and heapUsed .对于您的问题,您可能需要使用heapTotalheapUsed Depending on the value, you can then shut the service down.根据该值,您可以关闭该服务。 For example:例如:

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...
}

The division by one million part just converts bytes to megabytes (B to MB).除以一百万部分只是将字节转换为兆字节(B 到 MB)。

Change the code to what you like - this is just an example.将代码更改为您喜欢的代码 - 这只是一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM