Bird
0
0

You wrote this code to save a heap snapshot but it never finishes and the file is empty:

medium📝 Debug Q14 of 15
Node.js - Debugging and Profiling
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?
AwriteFileSync overwrites file on each data event, so file ends empty
BgetHeapSnapshot does not return a stream
CMissing 'end' event handler to finalize file writing
DwriteFileSync cannot write buffers
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes