Sub topic 14
Observing GC Behavior in Node.js and DevTools
This chapter assumes you know how WeakRef, deref(), and FinalizationRegistry work from earlier chapters. It also assumes you can run scripts with Node.js and open browser DevTools. The aim is to see collection happen during experiments. It does not show you how to rely on it.
Requesting a Collection in Node.js
Node.js normally gives you no way to start garbage collection. The --expose-gc flag adds a global gc() function that asks V8 to run a full collection. A call to gc() makes collection very likely, but the specification still does not promise that a given object will be collected or that a cleanup callback will run.
Each WeakRef target stays alive until the end of the current job. That means gc() must run in a later task, not in the same synchronous code that created or dereferenced the WeakRef.
// Run with: node --expose-gc observe.js
if (typeof globalThis.gc !== 'function') {
throw new Error('Run this script with: node --expose-gc observe.js');
}
const registry = new FinalizationRegistry((label) => {
console.log(`finalized: ${label}`);
});
let ref;
(function () {
const obj = { data: new Array(1_000_000).fill(0) };
ref = new WeakRef(obj);
registry.register(obj, 'big object');
})();
// Same job: the target is kept alive, so this is always true.
console.log('same job, alive:', ref.deref() !== undefined);
async function waitForCollection(weakRef, attempts = 10) {
for (let i = 0; i < attempts; i++) {
await new Promise((resolve) => setTimeout(resolve, 0)); // new job
globalThis.gc();
if (weakRef.deref() === undefined) return true;
}
return false;
}
waitForCollection(ref).then((collected) => {
console.log('collected:', collected);
// "finalized: big object" usually prints after this, in a later task.
});The output is usually same job, alive: true, then collected: true, then finalized: big object. The callback runs as its own task after collection, which is why it often prints last. On another engine version, or under different memory pressure, the result can be different.
Other Node.js Tools
| Tool | What it shows |
|---|---|
| `node --trace-gc app.js` | One log line per GC event, with heap sizes before and after |
| `process.memoryUsage()` | Current `heapUsed` and `heapTotal`, which you can compare before and after work |
| `node --inspect app.js` | Lets you attach Chrome DevTools to take heap snapshots of a Node process |
Using Chrome DevTools
In the Memory panel, the trash-can icon labelled Collect garbage forces a collection in the current page. To check whether an object can be collected:
- Take a heap snapshot.
- Run the code that should release the object.
- Click Collect garbage, then take a second snapshot.
- Pick the Comparison view, or search for your class name in the second snapshot.
If the object is still listed, select it and open the Retainers pane. That pane shows the chain of strong references keeping the object alive, such as a closure, an event listener, or a held value that points back to the target.
Testing Advice
- Put any test that calls
gc()behind a check thatglobalThis.gcexists, and skip it otherwise. - Always yield to a new task before calling
gc(), so the kept-alive rule forWeakReftargets does not hide a collection. - Limit retries and report "not collected" as a warning or a skipped test, not a hard failure.
Exercise
A script creates const ref = new WeakRef(obj), sets obj = null, calls globalThis.gc() on the next line, and then logs ref.deref(). It always prints the object. Why, and how do you fix the experiment?
Show answer
Creating the WeakRef added the target to the kept-alive list for the current job, so it cannot be collected until that synchronous job ends. Move the gc() call and the deref() check into a later task, for example inside setTimeout or after await new Promise(r => setTimeout(r, 0)).
Exercise
In DevTools, an object still appears in a heap snapshot after you click Collect garbage. Which pane helps you find the cause, and what does it show?
Show answer
The Retainers pane. It shows the chain of strong references from a GC root to the object, such as a closure, a listener, or a cache entry, so you can see what is keeping it alive.