{"id":12654,"library":"weak-napi","title":"weak-napi: N-API Weak References","description":"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.","status":"active","version":"2.0.2","language":"javascript","source_language":"en","source_url":"git://github.com/node-ffi-napi/weak-napi","tags":["javascript","weak","reference","js","object","function","callback","napi"],"install":[{"cmd":"npm install weak-napi","lang":"bash","label":"npm"},{"cmd":"yarn add weak-napi","lang":"bash","label":"yarn"},{"cmd":"pnpm add weak-napi","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"CommonJS import pattern for Node.js environments. The module exports a single function.","symbol":"weak (CJS)","correct":"const weak = require('weak-napi')"},{"note":"ES Module import pattern. 'weak-napi' exports a default function, not a named export. Node.js 6+ is required for full functionality.","wrong":"import { weak } from 'weak-napi'","symbol":"weak (ESM)","correct":"import weak from 'weak-napi'"}],"quickstart":{"code":"var weak = require('weak-napi');\n\n// We will monitor this object and invoke 'cleanup' after it's garbage collected\nlet obj = {\n    id: 'my-object',\n    data: Array(1000).fill('some data string') // Make it large enough to be GC'd\n};\n\n// Define the cleanup callback at a high scope to avoid strong references\nfunction cleanupCallback() {\n  console.log('\"obj\" with ID ' + this.id + ' has been garbage collected!');\n}\n\n// Create a weak reference to obj with the cleanup callback\n// Note: `this` inside the callback refers to the EventEmitter instance returned by `weak()`.\nconst ref = weak(obj, cleanupCallback);\nref.id = obj.id; // Store ID on the ref for logging in callback\n\nconsole.log('Weak reference created. Initial obj.id:', obj.id);\n\n// Dereference the object to allow it to be garbage collected\nobj = null;\n\nconsole.log('Original object reference cleared. Waiting for GC...');\n\n// In a real scenario, you'd let your application run.\n// For demonstration, we might try to force GC, but it's not reliable or recommended.\n// Global.gc is usually not available unless explicitly enabled with --expose-gc.\n// If process.env.EXPOSE_GC is set, you can try to call it:\nif (typeof global.gc === 'function') {\n  console.log('Attempting to force garbage collection...');\n  global.gc();\n  global.gc(); // Call twice for better chances\n} else {\n  console.log('Run Node.js with --expose-gc flag to see immediate callback execution via global.gc().');\n  console.log('Otherwise, the callback will eventually fire when V8 decides to run GC naturally.');\n}\n\n// Keep the process alive for a bit to allow GC to run naturally\nsetTimeout(() => {\n  console.log('Process ending. If GC ran, you should have seen the callback message.');\n}, 500);\n","lang":"javascript","description":"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."},"warnings":[{"fix":"Remove or refactor code that uses `isNearDeath()`. `weak-napi` does not provide an equivalent API.","message":"The `isNearDeath()` method is explicitly not supported and will always return `false`. Code relying on this method's prior functionality in `node-weak` will break or behave unexpectedly.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"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.","message":"Defining the GC callback function within the same scope as the object being weakly referenced can unintentionally create a strong reference to the object, preventing it from ever being garbage collected. This leads to memory leaks.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Upgrade your Node.js runtime environment to version 6 or newer. The latest LTS version is recommended for stability and security.","message":"`weak-napi` requires Node.js version 6 or higher due to its internal use of JavaScript `Proxy` objects. Running on older Node.js versions will result in runtime errors related to unsupported language features.","severity":"breaking","affected_versions":"<6.0.0"},{"fix":"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`.","message":"Although `weak-napi` uses N-API (which reduces recompilation issues), it is still a native Node.js addon. Compilation can fail if your system lacks necessary build tools (e.g., C++ compilers, Python, `node-gyp`).","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Run `npm rebuild weak-napi` in your project directory to recompile the native module against your current Node.js version.","cause":"The native addon was compiled for a different Node.js major version than the one currently running the application.","error":"Error: The module 'weak-napi.node' was compiled against a different Node.js version. This version of Node.js cannot load this module."},{"fix":"Upgrade your Node.js environment to version 6 or newer. Using a recent LTS version is highly recommended.","cause":"This error or similar Proxy-related errors occur when `weak-napi` is run on a Node.js version older than 6, which lacks full support for JavaScript Proxy objects.","error":"TypeError: Object.getOwnPropertyDescriptors called on non-object"},{"fix":"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.","cause":"A strong reference to the weakly-referenced object still exists somewhere in the application's memory, preventing the garbage collector from reclaiming it. A common culprit is defining the callback in a closure that captures the object.","error":"GC callback function not firing, or objects never appear to be garbage collected."},{"fix":"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.","cause":"The `weak-napi` native addon failed to compile during installation, or its compiled binary (`.node` file) is missing or corrupted.","error":"Error: Cannot find module 'weak-napi' or Error: The specified module could not be found."}],"ecosystem":"npm"}