Node.js › Global Objects & the process Object

What is process.memoryUsage(), and how would you use it to monitor a Node.js application's memory consumption?

Intermediate

Answer

process.memoryUsage() returns an object describing the current process's memory usage across several categories: rss (Resident Set Size, total memory allocated for the process including all C++ and JS objects), heapTotal and heapUsed (V8's JavaScript heap, allocated versus actually used), external (memory used by C++ objects bound to JavaScript objects, like Buffers), and arrayBuffers -- useful for building custom memory monitoring, alerting, or diagnosing suspected leaks by tracking these values over time.
setInterval(() => {
  const mem = process.memoryUsage();
  console.log({
    rss: `${(mem.rss / 1024 / 1024).toFixed(1)} MB`,
    heapUsed: `${(mem.heapUsed / 1024 / 1024).toFixed(1)} MB`,
  });
}, 30000);
Real-world example An operations team adds a periodic process.memoryUsage() log line to their application, feeding heapUsed into their monitoring dashboard, which lets them spot a slow, steady upward trend over several hours -- a telltale sign of a memory leak -- well before it would otherwise cause an out-of-memory crash.

Common follow-ups: Why can rss be significantly larger than heapUsed, and what does that difference represent?;How would you set up an automated alert to fire when heapUsed exceeds a certain threshold or shows a sustained upward trend?