{"id":14594,"library":"gcstats.js","title":"gcstats.js: V8 Garbage Collection Stats","description":"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.","status":"active","version":"1.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/bripkens/node-gcstats","tags":["javascript"],"install":[{"cmd":"npm install gcstats.js","lang":"bash","label":"npm"},{"cmd":"yarn add gcstats.js","lang":"bash","label":"yarn"},{"cmd":"pnpm add gcstats.js","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This package uses native C++ addons and is primarily designed for CommonJS. Direct ESM `import` is not supported without a wrapper or bundler configuration. The `gcStats` instance is an EventEmitter from which you subscribe to 'stats' events.","wrong":"import gcStats from 'gcstats.js';","symbol":"gcStats","correct":"const gcStats = require('gcstats.js');"}],"quickstart":{"code":"const gcStats = require('gcstats.js');\n\ngcStats.on('stats', function(stats) {\n  const gctypeMap = {\n    1: 'Scavenge (Minor GC)',\n    2: 'Mark/Sweep/Compact (Major GC)',\n    3: 'All GC Types'\n  };\n\n  console.log('--- GC Happened ---');\n  console.log(`Type: ${gctypeMap[stats.gctype] || 'Unknown'}`);\n  console.log(`Pause: ${(stats.pause / 1_000_000).toFixed(2)} ms`);\n  console.log(`Heap Used Before: ${(stats.before.usedHeapSize / (1024 * 1024)).toFixed(2)} MB`);\n  console.log(`Heap Used After: ${(stats.after.usedHeapSize / (1024 * 1024)).toFixed(2)} MB`);\n  console.log(`Total Heap Size: ${(stats.after.totalHeapSize / (1024 * 1024)).toFixed(2)} MB`);\n  console.log('-------------------\\n');\n});\n\n// Simulate some memory usage to trigger GC events periodically\nlet data = [];\nsetInterval(() => {\n  // Allocate new data\n  const allocationSizeMB = Math.random() * 5 + 5; // 5-10 MB\n  data.push(Buffer.alloc(Math.floor(allocationSizeMB * 1024 * 1024)));\n\n  // Periodically dereference old data to allow GC to reclaim memory\n  if (data.length > 10) {\n    data.splice(0, Math.floor(data.length / 2)); // Remove half of the old data\n  }\n  // Keep some data around to simulate a working application\n  console.log(`Current data array size: ${data.length}, total simulated memory: ${(data.reduce((sum, buf) => sum + buf.length, 0) / (1024 * 1024)).toFixed(2)} MB`);\n}, 500); // Trigger allocations every 500ms\n\nconsole.log('gcstats.js initialized. Simulating memory usage...');","lang":"javascript","description":"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."},"warnings":[{"fix":"After updating Node.js, run `npm rebuild gcstats.js` or `npm install gcstats.js` to recompile the native module. Always consult the project's `compatibility.md` for specific Node.js version support and known issues.","message":"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.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Ensure you have the required build tools for `node-gyp` installed on your operating system. For Windows, consider `npm install --global windows-build-tools`. For Linux/macOS, ensure development packages like `build-essential` (Debian/Ubuntu) or Xcode Command Line Tools (macOS) are installed.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Strictly use `require('gcstats.js')` in your code and `npm install gcstats.js` for package management to avoid module resolution errors.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Execute `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.","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.","error":"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."},{"fix":"Review 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.","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.","error":"Error: Cannot find module 'gcstats.js'"},{"fix":"Install 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.","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.","error":"Error: `node-gyp` failed to rebuild."}],"ecosystem":"npm"}