0
0
Node.jsframework~5 mins

Heap snapshot for memory leaks in Node.js

Choose your learning style9 modes available
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.