Course contentsShow
← Node.js
Lesson 1414 of 1,98013. Error Handling and Resilient SystemsFree lesson

Dumping Heap State on Crash

You will configure memory snapshots to be generated automatically upon fatal errors for post-mortem analysis.

In this lesson, you will learn how to configure your Node.js application to automatically capture a memory snapshot when it encounters a fatal crash, providing you with a "crime scene" for post-mortem debugging.

When a process terminates due to an uncaughtException, the memory state that led to the crash is usually lost forever. By generating a heap dump—a file that captures the entire contents of the V8 heap at a specific moment—you can load it into tools like Chrome DevTools or the llnode debugger to inspect exactly which objects were alive, what references were held, and which data structures might have caused an out-of-memory error or an unexpected state.

To automate this, you should use the heapdump library or the built-in --heapsnapshot-near-heap-limit flag. However, for a crash-specific trigger, you can hook into the uncaughtException event to generate the file before the process exits:

const v8 = require('v8');
const fs = require('fs');

process.on('uncaughtException', (err) => {
  const snapshotPath = `./heapdump-${Date.now()}.heapsnapshot`;
  
  // Write the current heap state to a file
  const snapshotStream = v8.writeHeapSnapshot(snapshotPath);
  
  console.error('Fatal crash detected. Snapshot saved to:', snapshotPath);
  
  // Exit the process after the snapshot is handled
  process.exit(1);
});

When an unhandled exception occurs, the code above uses v8.writeHeapSnapshot to serialize the memory contents. Because this operation is synchronous, it is best suited for the final moments of a lifecycle. Note that generating a heap dump is resource-intensive; it will pause your application and consume CPU/Disk I/O. Therefore, this should only be triggered during fatal exits where the process is dying anyway, rather than as a routine logging mechanism.

Once you have this .heapsnapshot file, you can drag and drop it into the "Memory" tab in Chrome DevTools. This allows you to explore the heap tree and identify the exact variables or circular references that contributed to your application's failure.

Key Takeaway: Automating heap snapshots on fatal crashes provides an invaluable forensic record, turning opaque runtime exceptions into transparent, inspectable memory states.