0
0
NodejsHow-ToBeginner · 3 min read

How to Get Memory Info in Node.js: Simple Guide

In Node.js, you can get memory information using the process.memoryUsage() method, which returns an object with details about the memory used by the Node.js process. This includes values like RSS, heap total, heap used, and external memory, all in bytes.
📐

Syntax

The process.memoryUsage() method returns an object with memory usage details of the current Node.js process.

  • rss: Resident Set Size - total memory allocated for the process.
  • heapTotal: Total size of the allocated heap.
  • heapUsed: Actual memory used during the execution.
  • external: Memory used by C++ objects bound to JavaScript objects.
javascript
const memoryInfo = process.memoryUsage();
console.log(memoryInfo);
Output
{ rss: 21585920, heapTotal: 5734400, heapUsed: 3401232, external: 8272 }
💻

Example

This example shows how to get memory info and print it in a readable format with values converted to megabytes.

javascript
function formatMemory(memory) {
  return (memory / 1024 / 1024).toFixed(2) + ' MB';
}

const memoryInfo = process.memoryUsage();

console.log('Memory Usage:');
console.log('RSS:', formatMemory(memoryInfo.rss));
console.log('Heap Total:', formatMemory(memoryInfo.heapTotal));
console.log('Heap Used:', formatMemory(memoryInfo.heapUsed));
console.log('External:', formatMemory(memoryInfo.external));
Output
Memory Usage: RSS: 20.58 MB Heap Total: 5.47 MB Heap Used: 3.24 MB External: 0.01 MB
⚠️

Common Pitfalls

Some common mistakes when getting memory info in Node.js include:

  • Expecting memory values in megabytes directly; process.memoryUsage() returns bytes, so conversion is needed.
  • Misunderstanding rss as only heap memory; it includes all memory allocated for the process.
  • Not considering that memory usage can fluctuate rapidly during runtime.
javascript
/* Wrong: Assuming memoryUsage returns MB directly */
const memWrong = process.memoryUsage();
console.log('Heap Used (wrong):', memWrong.heapUsed);

/* Right: Convert bytes to MB */
const memRight = process.memoryUsage();
console.log('Heap Used (right):', (memRight.heapUsed / 1024 / 1024).toFixed(2) + ' MB');
Output
Heap Used (wrong): 3401232 Heap Used (right): 3.24 MB
📊

Quick Reference

PropertyDescription
rssTotal memory allocated for the process (includes heap, stack, and native code)
heapTotalTotal size of the allocated heap memory
heapUsedActual memory used in the heap
externalMemory used by C++ objects bound to JavaScript objects

Key Takeaways

Use process.memoryUsage() to get detailed memory info in bytes.
Convert bytes to megabytes for easier reading and understanding.
rss includes all memory allocated to the process, not just heap.
Memory usage can change quickly; check it at the right time.
Avoid assuming memory values are in MB without conversion.