process.memoryUsage Measures Heap Before And After
Read process.memoryUsage around a workload and correlate rss, heapUsed, and heapTotal deltas so leaks show up as deltas, not folklore.
Code
function snapshot(label) {
const m = process.memoryUsage();
const mb = (n) => `${(n / 1024 / 1024).toFixed(1)} MB`;
console.log(`${label}: rss ${mb(m.rss)}, heapUsed ${mb(m.heapUsed)}, heapTotal ${mb(m.heapTotal)}`);
return m;
}
const before = snapshot('before');
// A bounded workload: buffers are allocated then explicitly dropped.
const chunks = [];
for (let i = 0; i < 50; i++) {
chunks.push(Buffer.alloc(1024 * 1024, i));
}
console.log('allocated:', chunks.length, 'chunks x 1 MB');
const during = snapshot('during');
console.log('heap delta: +', ((during.heapUsed - before.heapUsed) / 1024 / 1024).toFixed(1), 'MB');
chunks.length = 0; // release the references
const after = snapshot('after (GC may lag until the next collection)');
console.log('rss never measures the object graph directly — heapUsed does');Output
Captured from a sandboxed run of this snippet in the build pipeline.
before: rss 48.9 MB, heapUsed 4.0 MB, heapTotal 6.2 MB
allocated: 50 chunks x 1 MB
during: rss 98.8 MB, heapUsed 4.6 MB, heapTotal 6.4 MB
heap delta: + 0.6 MB
after (GC may lag until the next collection): rss 98.8 MB, heapUsed 4.6 MB, heapTotal 6.4 MB
rss never measures the object graph directly — heapUsed doesWhat the file does
Everything happens inside the functions mb and snapshot.
The loop for (let i = 0; i < 50; i++) is the only repeated construct.
What to watch for
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
Putting it to use
The signature in play is const mb = (n)
Output lines are prefixed (allocated:, heap delta: +), which keeps every step’s outcome observable.
Lines that carry the behavior
const mb = (n) => `${(n / 1024 / 1024).toFixed(1)} MB`;
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `mb`, `snapshot` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.