Home > OS >  How to programmatically know when NodeJS application is running out of memory
How to programmatically know when NodeJS application is running out of memory

Time:04-11

How can I know when my application is running out of memory.

For me, I'm doing some video transcoding on the server and sometimes it leads to out of memory errors.

So, I wish to know when the application is running out of memory so I can immediately kill the Video Transcoder.

Thank you.

CodePudding user response:

You can see how much memory is being used with the built-in process module.

const process = require("process");

The process module has a method called memoryUsage, which shows info on the memory usage in Node.js.

console.log(process.memoryUsage());

When you run the code, you should see an object with all of the information needed for memory usage!

$ 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.
  • heapTotal - The total amount of memory in the V8 engine.
  • heapUsed - The amount of memory used by the V8 engine.
  • external - The memory usage of C objects bound to JavaScript objects (managed by V8).
  • arrayBuffers - The memory allocated for ArrayBuffers and Buffers.

For your question, you might need to use heapTotal and heapUsed. 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 me!

if ((mem.heapUsed / 1000000) >= MAX_SIZE) {
  videoTranscoder.kill(); // You get the idea...
}

The division by one million part just converts bytes to megabytes (B to MB).

Change the code to what you like - this is just an example.

  • Related