Note: This article first appeared on dev.to
In diagnosing memory leaks, one of the most useful tools in a developer’s aresenal is the heap dump, or heap snapshot, which gives us insight into what objects are allocated on the JavaScript, and how many of them.
The Old Way
Traditionally, in Node.js, we’ve had two options for creating heap dumps.
- Using the
heapdump
module. - Attaching a Chrome DevTools instance and using the Memory tab to create a heap snapshot.
In cases where it’s feasible and simple, the second option is usually best, since it requires no additional software, and has a simple point-and-click interface to get the job done.
In production environments, it’s often not an option, so users are left using the heapdump
module. While this generally works without issue, there is an additional compilation step and a module to install in order to get this done. These are obivously not insurmountable hurdles, but they can get in the way of solving a problem quickly.
The New Way
The good news is that in newer versions of Node.js, you don’t need the external module, since heap dump functionality is now part of the core API, as of Node.js v12.
To create a heap snapshot, you can just use v8.getHeapSnapshot()
. This returns a readable stream, which you can then pipe to a file, which you can then use in Chrome DevTools.
For example, you can make a function like this that you can call whenever you want to create a heap dump file.
constfs=require('fs');constv8=require('v8');functioncreateHeapSnapshot(){constsnapshotStream=v8.getHeapSnapshot();// It's important that the filename end with `.heapsnapshot`,// otherwise Chrome DevTools won't open it.constfileName=`${Date.now()}.heapsnapshot`;constfileStream=fs.createWriteStream(fileName);snapshotStream.pipe(fileStream);}
You can call this function on a regular basis using setInterval
, or you can set a signal handler or some other mechanism to trigger the heap dumps manually.
This new API function is available in all currently supported release lines of Node.js except for v10, where you’ll still need the heapdump
module for similar functionality.
Feel free to use the snippet above in your own applications whenever trying to diagnose memory leaks in the future. Happy debugging!