Bird
Raised Fist0
Node.jsframework~5 mins

Heap snapshot for memory leaks in Node.js

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

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.

When your Node.js app gets slower over time and uses more memory.
When you want to find out which parts of your code keep objects in memory.
When you want to check if your app frees memory properly after tasks.
When debugging crashes caused by running out of memory.
When optimizing memory usage to improve app performance.
Syntax
Node.js
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.

Examples
Basic example saving a snapshot to snapshot1.heapsnapshot.
Node.js
const v8 = require('v8');
const fs = require('fs');

// Save heap snapshot to file
v8.getHeapSnapshot().pipe(fs.createWriteStream('snapshot1.heapsnapshot'));
You can take multiple snapshots at different times to compare memory usage.
Node.js
// 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'));
Modern async/await style to save snapshot, requires Node.js 20 or newer.
Node.js
// 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();
Sample Program

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.

Node.js
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.');
});
OutputSuccess
Important Notes

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.

Summary

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

(1/5)
1. What is the main purpose of taking a heap snapshot in Node.js?
easy
A. To monitor network requests
B. To speed up the execution of code
C. To compile the Node.js application
D. To see what objects are currently in memory

Solution

  1. Step 1: Understand heap snapshot concept

    A heap snapshot captures the objects currently stored in memory at a specific time.
  2. Step 2: Identify the purpose of heap snapshots

    They help detect memory leaks by showing which objects remain in memory longer than expected.
  3. Final Answer:

    To see what objects are currently in memory -> Option D
  4. Quick Check:

    Heap snapshot = current memory objects [OK]
Hint: Heap snapshots show memory objects at a moment [OK]
Common Mistakes:
  • Thinking heap snapshots speed up code
  • Confusing heap snapshots with network monitoring
  • Assuming heap snapshots compile code
2. Which Node.js module provides the getHeapSnapshot() method to create heap snapshots?
easy
A. fs
B. v8
C. http
D. os

Solution

  1. Step 1: Recall Node.js modules for memory tools

    The v8 module provides access to V8 engine features including heap snapshots.
  2. Step 2: Match method to module

    The getHeapSnapshot() method is part of the v8 module, not fs, http, or os.
  3. Final Answer:

    v8 -> Option B
  4. Quick Check:

    Heap snapshot method = v8 module [OK]
Hint: Heap snapshot method is in v8 module [OK]
Common Mistakes:
  • Choosing fs for file operations only
  • Confusing http with memory tools
  • Selecting os which handles system info
3. Consider this Node.js code snippet:
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?
medium
A. Create an empty file named 'heap.heapsnapshot' only
B. Throw an error because getHeapSnapshot is not a function
C. Save a heap snapshot file and print 'Snapshot saved'
D. Print 'Snapshot saved' without creating any file

Solution

  1. Step 1: Analyze getHeapSnapshot usage

    The getHeapSnapshot() returns a readable stream of the heap snapshot data.
  2. 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.
  3. Final Answer:

    Save a heap snapshot file and print 'Snapshot saved' -> Option C
  4. Quick Check:

    Heap snapshot stream saved to file [OK]
Hint: getHeapSnapshot returns stream; collect and save it [OK]
Common Mistakes:
  • Assuming getHeapSnapshot returns a buffer directly
  • Expecting no file creation
  • Thinking it throws an error
4. You wrote this code to save a heap snapshot but it never finishes and the file is empty:
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?
medium
A. writeFileSync overwrites file on each data event, so file ends empty
B. getHeapSnapshot does not return a stream
C. Missing 'end' event handler to finalize file writing
D. writeFileSync cannot write buffers

Solution

  1. Step 1: Examine file writing inside 'data' event

    Calling writeFileSync inside 'data' overwrites the file each time a chunk arrives.
  2. 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.
  3. Final Answer:

    writeFileSync overwrites file on each data event, so file ends empty -> Option A
  4. Quick Check:

    File overwritten repeatedly in data event [OK]
Hint: Write all chunks after stream ends, not during data event [OK]
Common Mistakes:
  • Assuming getHeapSnapshot is not a stream
  • Ignoring need for 'end' event
  • Thinking writeFileSync can't write buffers
5. You want to detect a memory leak in your Node.js app by comparing heap snapshots over time. Which approach is best?
hard
A. Take multiple heap snapshots at intervals and compare retained objects
B. Only take one snapshot at app start and analyze it
C. Use console.log to print all objects in memory continuously
D. Restart the app frequently to clear memory

Solution

  1. Step 1: Understand memory leak detection

    Memory leaks show as objects that remain in memory longer than expected, growing over time.
  2. Step 2: Use heap snapshots over time

    Taking snapshots at intervals lets you compare and find objects that accumulate, indicating leaks.
  3. Step 3: Evaluate other options

    One snapshot can't show growth; console.log is impractical; restarting hides leaks instead of detecting.
  4. Final Answer:

    Take multiple heap snapshots at intervals and compare retained objects -> Option A
  5. Quick Check:

    Compare snapshots over time to find leaks [OK]
Hint: Compare snapshots over time to spot leaks [OK]
Common Mistakes:
  • Relying on a single snapshot
  • Using console.log for memory objects
  • Restarting app to avoid leaks instead of fixing