gcstats.js: V8 Garbage Collection Stats
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
-
Error: The `gcstats.js` module was compiled against a different Node.js version than the one you are currently running. This may cause runtime errors or segfaults.
cause The native C++ addon was compiled for a Node.js Application Binary Interface (ABI) that does not match your current Node.js runtime environment. This commonly occurs after upgrading or downgrading Node.js.fixExecute `npm rebuild gcstats.js` or `npm install gcstats.js` in your project directory to recompile the native module against your current Node.js version. Ensure `node-gyp` prerequisites are met. -
Error: Cannot find module 'gcstats.js'
cause The native addon failed to compile during the `npm install` process, or the package was not installed correctly, leading to the absence of the compiled binary.fixReview the installation logs carefully for `node-gyp` errors. Ensure all required build tools are installed. Try running `npm install gcstats.js` again, potentially with `--force` or clearing npm cache. -
Error: `node-gyp` failed to rebuild.
cause This error message (or similar `gyp` errors in install logs) indicates a problem with the `node-gyp` compilation process, often due to missing C++ compilers, Python, or other development tools on the system.fixInstall the necessary build tools as per `node-gyp`'s documentation for your operating system. Common solutions include `npm install --global windows-build-tools` on Windows, or installing `build-essential` on Linux and Xcode Command Line Tools on macOS.
Warnings
- breaking This package relies on native C++ addons, which must be compiled for your specific Node.js version and architecture during installation. Compatibility can break with new major Node.js releases (especially those with V8 ABI changes), requiring a re-install or an update to a compatible package version.
- gotcha Installation may fail if necessary build tools are not present on the system (e.g., Python 2.x/3.x, C++ compiler, `make`). `node-gyp` is used for compilation, which has specific system requirements.
- gotcha The npm package name is `gcstats.js`, but internal documentation and some references (e.g., in `compatibility.md`) might refer to the native module component as `gc-stats`. Always use `gcstats.js` for `require()` statements and npm commands.
Install
-
npm install gcstats.js -
yarn add gcstats.js -
pnpm add gcstats.js
Imports
- gcStats
import gcStats from 'gcstats.js';
const gcStats = require('gcstats.js');
Quickstart
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...');