Blog>
Snippets

Monitoring Memory Usage with Node.js

Use Node.js process memory methods like `process.memoryUsage()` to monitor and log memory consumption, helping to detect memory leaks in server-side JavaScript applications.
setInterval(() => {
    const memoryUsage = process.memoryUsage();
    console.log(`Memory Usage:
- RSS: ${memoryUsage.rss} bytes
- Heap Total: ${memoryUsage.heapTotal} bytes
- Heap Used: ${memoryUsage.heapUsed} bytes
- External: ${memoryUsage.external} bytes
- Array Buffers: ${memoryUsage.arrayBuffers} bytes`);
}, 10000);
Sets an interval that logs the memory usage of the Node.js process every 10 seconds. RSS indicates the Resident Set Size, heapTotal and heapUsed are related to the V8 heap memory, external indicates the memory used by C++ objects bound to JavaScript objects managed by V8, and arrayBuffers indicates allocated memory for ArrayBuffers and SharedArrayBuffers. This interval can help detect memory growth over time, which could indicate a memory leak.