gcstats.js: V8 Garbage Collection Stats

1.0.0 · active · verified Sun Apr 19

gcstats.js is a Node.js package that provides granular statistics about V8 garbage collection events. It exposes a native binding that emits 'stats' events whenever a garbage collection cycle completes, detailing various heap metrics before and after the GC, including `totalHeapSize`, `usedHeapSize`, `totalHeapExecutableSize`, `heapSizeLimit`, `totalPhysicalSize`, and the `gctype` (Scavenge, Mark/Sweep/Compact, or both). The current stable version is 1.0.0. While there isn't a stated release cadence, updates are typically driven by compatibility requirements with new Node.js V8 engine versions or bug fixes. Its key differentiator is direct access to low-level V8 GC information, which is otherwise difficult to obtain without `--expose-gc` flags and manual polling, making it invaluable for performance monitoring and debugging memory-intensive Node.js applications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize gcstats.js and subscribe to 'stats' events, logging detailed garbage collection metrics including type, pause duration, and heap usage before/after. It includes a robust memory allocation simulation to reliably trigger and showcase GC events.

const gcStats = require('gcstats.js');

gcStats.on('stats', function(stats) {
  const gctypeMap = {
    1: 'Scavenge (Minor GC)',
    2: 'Mark/Sweep/Compact (Major GC)',
    3: 'All GC Types'
  };

  console.log('--- GC Happened ---');
  console.log(`Type: ${gctypeMap[stats.gctype] || 'Unknown'}`);
  console.log(`Pause: ${(stats.pause / 1_000_000).toFixed(2)} ms`);
  console.log(`Heap Used Before: ${(stats.before.usedHeapSize / (1024 * 1024)).toFixed(2)} MB`);
  console.log(`Heap Used After: ${(stats.after.usedHeapSize / (1024 * 1024)).toFixed(2)} MB`);
  console.log(`Total Heap Size: ${(stats.after.totalHeapSize / (1024 * 1024)).toFixed(2)} MB`);
  console.log('-------------------\n');
});

// Simulate some memory usage to trigger GC events periodically
let data = [];
setInterval(() => {
  // Allocate new data
  const allocationSizeMB = Math.random() * 5 + 5; // 5-10 MB
  data.push(Buffer.alloc(Math.floor(allocationSizeMB * 1024 * 1024)));

  // Periodically dereference old data to allow GC to reclaim memory
  if (data.length > 10) {
    data.splice(0, Math.floor(data.length / 2)); // Remove half of the old data
  }
  // Keep some data around to simulate a working application
  console.log(`Current data array size: ${data.length}, total simulated memory: ${(data.reduce((sum, buf) => sum + buf.length, 0) / (1024 * 1024)).toFixed(2)} MB`);
}, 500); // Trigger allocations every 500ms

console.log('gcstats.js initialized. Simulating memory usage...');

view raw JSON →