Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor maximum memory consumption in Node.js process

Tags:

I'm looking for a cross-platform way to reliably monitor maximum memory consumption in Node.js process, regardless of whether there are leaks or not.

The processes in my case are both real applications and synthetic tests.

I would expect it to work like

process.on('exit', () => {   console.log('Max memory consumption: ' + ...); }); 

It was possible to trace memory consumption somehow with node --trace_gc ..., but this resulted in output that is hard to read (and probably hard to analyze programmatically). Also, GC didn't occur when a script ended too fast, even if RAM usage was substantial.

From what I have seen on the subject, usually memwatch is suggested for that, like:

require('memwatch-next').on('stats', stats => {   console.log('Max memory consumption: ' + stats.max); }); 

But in my case it triggered only when GC already happened or didn't trigger at all, so it was useless for determining RAM consumption peaks.

I would prefer to avoid GUI tools like node-inspector if possible.

Can this maximum memory consumption be reliably retrieved as a number from the application itself or CLI alone, cross-platform?

like image 339
Estus Flask Avatar asked Jun 29 '17 15:06

Estus Flask


Video Answer


1 Answers

You could use Node.js process.memoryUsage() method to get memory usage stat:

The process.memoryUsage() method returns an object describing the memory usage of the Node.js process measured in bytes.

It returns the object of the following format:

{   rss: 4935680,       // Resident Set Size   heapTotal: 1826816, // Total Size of the Heap   heapUsed: 650472,   // Heap actually Used   external: 49879     // memory usage of C++ objects bound to JavaScript objects managed by V8 } 

To get the maximum memory consumption in Node.js process, process.nextTick method could be used. process.nextTick() method adds the callback to the next tick queue. Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.

let _maxMemoryConsumption = 0; let _dtOfMaxMemoryConsumption;  process.nextTick(() => {   let memUsage = process.memoryUsage();   if (memUsage.rss > _maxMemoryConsumption) {     _maxMemoryConsumption = memUsage.rss;     _dtOfMaxMemoryConsumption = new Date();   } });  process.on('exit', () => {   console.log(`Max memory consumption: ${_maxMemoryConsumption} at ${_dtOfMaxMemoryConsumption}`); }); 
like image 103
alexmac Avatar answered Sep 22 '22 08:09

alexmac