javascript / expert
Snippet
Programmatic Memory Profiling in Node.js
Using the 'v8' module, Node.js applications can programmatically generate heap snapshots. When combined with manual garbage collection (via the --expose-gc flag), this allows for precise memory leak detection and diagnostic reporting directly from the production runtime.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import v8 from 'node:v8';import fs from 'node:fs';function analyzeMemory() {if (typeof global.gc === 'function') {global.gc(); // Manual GC trigger (requires --expose-gc)}const stream = v8.getHeapSnapshot();const fileName = `${Date.now()}.heapsnapshot`;stream.pipe(fs.createWriteStream(fileName));console.log(`Snapshot saved: ${fileName}`);}
nodejs
Breakdown
1
global.gc();
Forcing a garbage collection cycle to clear out unreachable objects before taking a snapshot.
2
v8.getHeapSnapshot();
Returns a readable stream containing the current V8 heap state.