weak-napi is a Node.js module that provides functionality for creating weak references to JavaScript objects and registering callbacks that execute upon an object's garbage collection. It exposes the underlying V8 engine's GC tracking features, which are otherwise inaccessible from JavaScript. The current stable version is 2.0.2, with a release cadence primarily focused on N-API compatibility and stability. A key differentiator from its predecessor, `node-weak`, is its utilization of N-API, eliminating the need for recompilation across different Node.js versions and improving the robustness of GC callbacks to prevent crashes. It requires Node.js 6 or newer due to its reliance on Proxy objects for comprehensive property handling, and notably does not support the `isNearDeath()` API. This module is commonly employed for debugging memory leaks and understanding the lifecycle of objects within Node.js applications.
npm install weak-napiVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to create a weak reference to an object and register a callback function to be executed when the object is garbage collected. It highlights best practices for callback placement and the process of dereferencing the original object. Due to the non-deterministic nature of garbage collection, the callback's execution time is not guaranteed without explicitly exposing V8's GC via Node.js `--expose-gc` flag.
Remove or refactor code that uses `isNearDeath()`. `weak-napi` does not provide an equivalent API.
Always define GC callback functions in the highest possible scope (e.g., top-level or a module-level named function) to ensure they do not capture a strong reference to the target object. Refer to 'Weak Callback Function "Best Practices"' in the documentation.
Upgrade your Node.js runtime environment to version 6 or newer. The latest LTS version is recommended for stability and security.
Ensure you have the appropriate build tools installed for your operating system (e.g., `windows-build-tools` for Windows, `build-essential` for Linux, Xcode Command Line Tools for macOS). If issues persist, try `npm rebuild weak-napi`.
Run `npm rebuild weak-napi` in your project directory to recompile the native module against your current Node.js version.
Upgrade your Node.js environment to version 6 or newer. Using a recent LTS version is highly recommended.
Review your code to ensure no strong references remain to the object after `obj = null;`. Pay close attention to the scope where your GC callback is defined, ensuring it doesn't close over the `obj` variable itself.
Check the `npm install` logs for any compilation errors. Ensure you have required build tools (like `node-gyp` and a C++ compiler) installed. Then run `npm rebuild weak-napi` to attempt recompilation.
No dependency data recorded yet.