Node.js · Senior · Question 5 of 75

Why can a closure cause unexpected memory retention?

function handler(req) {
  const hugeBody = req.body; // 50 MB
  const id = hugeBody.id;
  emitter.on("done", () => console.log(id));
}

Explanation

The real bug is the listener that is never removed. V8 may also keep variables of a shared context alive. Remove listeners, use once, and don't capture large objects.

Further reading

Problem with a question

Node.js · Senior · question 5

Test yourself

Take the Node.js · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz