Stop worrying about the potholes in the road and enjoy the journey

How to Monitor Memory Usage in Your Node.js Application

Understanding how much memory your Node.js application consumes is essential for optimizing performance and preventing memory leaks. Node.js provides built-in tools to check memory usage programmatically, and there are also external tools for real-time monitoring.

1. Using process.memoryUsage()

The process.memoryUsage() method in Node.js provides detailed information about the memory consumption of the current process. Here's a basic example:

console.log('Memory usage:', process.memoryUsage());

This will output an object with the following fields:

  • rss: Resident Set Size - total memory used by the process, including code, data, and allocated memory.
  • heapTotal: Total memory allocated for the JavaScript heap.
  • heapUsed: Memory currently used by JavaScript objects.
  • external: Memory used by C++ objects bound to Node.js.

An example output:

{
  "rss": 33157120,
  "heapTotal": 7385088,
  "heapUsed": 4812560,
  "external": 8272
}

2. Formatting Memory Usage for Readability

To make the output more user-friendly, you can format the values in megabytes:

function formatMemoryUsage(memory) {
    return {
        rss: `${(memory.rss / 1024 / 1024).toFixed(2)} MB`,
        heapTotal: `${(memory.heapTotal / 1024 / 1024).toFixed(2)} MB`,
        heapUsed: `${(memory.heapUsed / 1024 / 1024).toFixed(2)} MB`,
        external: `${(memory.external / 1024 / 1024).toFixed(2)} MB`
    };
}

console.log('Memory usage:', formatMemoryUsage(process.memoryUsage()));

3. Real-Time Memory Monitoring

If you'd like to monitor memory usage in real time, you can set up a periodic log using setInterval:

setInterval(() => {
    console.log('Memory usage:', formatMemoryUsage(process.memoryUsage()));
}, 5000); // Every 5 seconds

4. Monitoring Memory Usage Externally

For cases where you want to check memory usage from another terminal or without modifying your code, here are some options:

4.1. Using System Commands

On Linux/Unix:

ps aux | grep node
top -p <PID>

On Windows:

tasklist | findstr node

Then, you can monitor memory usage with tools like top, htop, or the Task Manager on Windows.

4.2. Using the pidusage Library

The pidusage package is a convenient tool to track memory and CPU usage for any Node.js process. Install it with:

npm install pidusage

Here's an example usage:

import pidusage from 'pidusage';

setInterval(async () => {
    const stats = await pidusage(process.pid);
    console.log(`Memory: ${(stats.memory / 1024 / 1024).toFixed(2)} MB`);
}, 5000);

Conclusion

To monitor memory usage effectively:

  • Use process.memoryUsage() for built-in insights into your application's memory consumption.
  • Format the output for better readability if needed.
  • For real-time monitoring, leverage periodic logging or external tools like pidusage, top, or htop.

These techniques can help you keep your Node.js applications optimized and prevent memory issues from impacting performance.

1