A heap snapshot helps you see what is using memory in your Node.js app. It helps find memory leaks by showing objects that stay in memory too long.
Heap snapshot for memory leaks in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
const v8 = require('v8'); // Take a heap snapshot and save it to a file const fs = require('fs'); const snapshotStream = v8.getHeapSnapshot(); const fileStream = fs.createWriteStream('heap.heapsnapshot'); snapshotStream.pipe(fileStream); fileStream.on('finish', () => { console.log('Heap snapshot saved to heap.heapsnapshot'); });
This code uses Node.js built-in v8 module to get a heap snapshot.
The snapshot is saved as a file you can open in Chrome DevTools for analysis.
snapshot1.heapsnapshot.const v8 = require('v8'); const fs = require('fs'); // Save heap snapshot to file v8.getHeapSnapshot().pipe(fs.createWriteStream('snapshot1.heapsnapshot'));
// Taking multiple snapshots const v8 = require('v8'); const fs = require('fs'); v8.getHeapSnapshot().pipe(fs.createWriteStream('snapshot1.heapsnapshot')); v8.getHeapSnapshot().pipe(fs.createWriteStream('snapshot2.heapsnapshot'));
// Using async/await with streams (Node.js 20+) import { createWriteStream } from 'fs'; import { getHeapSnapshot } from 'v8'; async function saveSnapshot() { const snapshotStream = getHeapSnapshot(); const fileStream = createWriteStream('snapshot_async.heapsnapshot'); await new Promise((resolve, reject) => { snapshotStream.pipe(fileStream); fileStream.on('finish', resolve); fileStream.on('error', reject); }); console.log('Snapshot saved with async/await'); } saveSnapshot();
This program creates some objects to use memory, then takes a heap snapshot and saves it to a file. You can open the file in Chrome DevTools to see what is using memory.
const v8 = require('v8'); const fs = require('fs'); console.log('Starting heap snapshot example'); // Simulate memory usage const memoryHolder = []; for (let i = 0; i < 10000; i++) { memoryHolder.push({ index: i, data: 'some data ' + i }); } console.log('Memory allocated, taking heap snapshot...'); const snapshotStream = v8.getHeapSnapshot(); const fileStream = fs.createWriteStream('example.heapsnapshot'); snapshotStream.pipe(fileStream); fileStream.on('finish', () => { console.log('Heap snapshot saved to example.heapsnapshot'); console.log('You can open this file in Chrome DevTools to analyze memory usage.'); });
Heap snapshot files can be large; keep that in mind when saving many snapshots.
Time complexity depends on the size of the heap; snapshots may take a few seconds.
Common mistake: forgetting to close the file stream or not waiting for 'finish' event before using the snapshot file.
Use heap snapshots when you suspect memory leaks or want to optimize memory usage. For quick checks, Node.js built-in --inspect flag with DevTools can also help.
Heap snapshots show what objects are in memory at a moment.
They help find memory leaks by showing objects that stay longer than expected.
Use Node.js v8.getHeapSnapshot() to create and save snapshots for analysis.
Practice
Solution
Step 1: Understand heap snapshot concept
A heap snapshot captures the objects currently stored in memory at a specific time.Step 2: Identify the purpose of heap snapshots
They help detect memory leaks by showing which objects remain in memory longer than expected.Final Answer:
To see what objects are currently in memory -> Option DQuick Check:
Heap snapshot = current memory objects [OK]
- Thinking heap snapshots speed up code
- Confusing heap snapshots with network monitoring
- Assuming heap snapshots compile code
getHeapSnapshot() method to create heap snapshots?Solution
Step 1: Recall Node.js modules for memory tools
Thev8module provides access to V8 engine features including heap snapshots.Step 2: Match method to module
ThegetHeapSnapshot()method is part of thev8module, notfs,http, oros.Final Answer:
v8 -> Option BQuick Check:
Heap snapshot method = v8 module [OK]
- Choosing fs for file operations only
- Confusing http with memory tools
- Selecting os which handles system info
import { writeFileSync } from 'fs';
import { getHeapSnapshot } from 'v8';
const snapshotStream = getHeapSnapshot();
const chunks = [];
snapshotStream.on('data', chunk => chunks.push(chunk));
snapshotStream.on('end', () => {
writeFileSync('heap.heapsnapshot', Buffer.concat(chunks));
console.log('Snapshot saved');
});
What will this code do when run?Solution
Step 1: Analyze getHeapSnapshot usage
ThegetHeapSnapshot()returns a readable stream of the heap snapshot data.Step 2: Understand stream data handling
The code collects data chunks from the stream, concatenates them, and writes to 'heap.heapsnapshot'. Then it logs confirmation.Final Answer:
Save a heap snapshot file and print 'Snapshot saved' -> Option CQuick Check:
Heap snapshot stream saved to file [OK]
- Assuming getHeapSnapshot returns a buffer directly
- Expecting no file creation
- Thinking it throws an error
import { writeFileSync } from 'fs';
import { getHeapSnapshot } from 'v8';
const snapshotStream = getHeapSnapshot();
snapshotStream.on('data', chunk => {
writeFileSync('heap.heapsnapshot', chunk);
});
console.log('Snapshot saved');
What is the main problem?Solution
Step 1: Examine file writing inside 'data' event
CallingwriteFileSyncinside 'data' overwrites the file each time a chunk arrives.Step 2: Understand effect on file content
Because of overwriting, only the last chunk remains, or file may appear empty if last chunk is empty.Final Answer:
writeFileSync overwrites file on each data event, so file ends empty -> Option AQuick Check:
File overwritten repeatedly in data event [OK]
- Assuming getHeapSnapshot is not a stream
- Ignoring need for 'end' event
- Thinking writeFileSync can't write buffers
Solution
Step 1: Understand memory leak detection
Memory leaks show as objects that remain in memory longer than expected, growing over time.Step 2: Use heap snapshots over time
Taking snapshots at intervals lets you compare and find objects that accumulate, indicating leaks.Step 3: Evaluate other options
One snapshot can't show growth; console.log is impractical; restarting hides leaks instead of detecting.Final Answer:
Take multiple heap snapshots at intervals and compare retained objects -> Option AQuick Check:
Compare snapshots over time to find leaks [OK]
- Relying on a single snapshot
- Using console.log for memory objects
- Restarting app to avoid leaks instead of fixing
