Sitemap

Watching the Memory Usage of a NodeJS Process

2 min readMay 11, 2023
“Watercolor of exploding computer” by Dall-E2

Sometimes we need to observe the memory usage of a NodeJS program in order to fix leaks. This is never an easy task but the good news is that you don’t need to modify a NodeJS program in order to monitor its memory usage. Instead, you can connect the NodeJS debugger to a running process, at least before it crashes.

  1. Save this example NodeJS program as mem.js. It crashes with an out of memory error after a few minutes (depending on machine resources).
buffer = []; // This array grows until the process runs out of memory

useMem = () => {
for (i = 0; i < 1000; ++i) buffer.push(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
};

setInterval(useMem, 10);

2. Run mem.js in inspect mode

node --inspect mem.js

3. Find the pid of the node process

pgrep -f "node --inspect"

4. Run the debugger using the output of the above command

node inspect -p <pid>

5. View the process’s memory usage in the debugger

debug> process.memoryUsage()
{
rss: 35176448,
heapTotal: 9199616,
heapUsed: 5307840,
external: 5061141,
arrayBuffers: 63730
}

Repeat the last step and watch the memory utilization increase.

If it takes too long for the program to crash, try something like this before running the NodeJS program:

export NODE_OPTIONS="--max-old-space-size=512"

--

--

Terris Linenbach
Terris Linenbach

Written by Terris Linenbach

Coder since 1980. Always seeking the Best Way. CV: https://terris.com/cv

No responses yet