Sometimes, we want to monitor the memory usage of Node.js.
In this article, we’ll look at how to monitor the memory usage of Node.js.
How to monitor the memory usage of Node.js?
To monitor the memory usage of Node.js, we use the process.memoryUsage method.
For instance, we write
const formatMemoryUsage = (data) =>
`${Math.round((data / 1024 / 1024) * 100) / 100} MB`;
const memoryData = process.memoryUsage();
const memoryUsage = {
rss: formatMemoryUsage(memoryData.rss),
heapTotal: formatMemoryUsage(memoryData.heapTotal),
heapUsed: formatMemoryUsage(memoryData.heapUsed),
external: formatMemoryUsage(memoryData.external),
};
console.log(memoryUsage);
to get an object that various properties.
rss is the Resident Set Size, which is the total memory allocated for the process execution.
heapTotal is the total size of the allocated heap.
heapUsed is the amount of memory used.
external is the V8 external memory amount.
All values are in bytes.
Conclusion
To monitor the memory usage of Node.js, we use the process.memoryUsage method.