How do you prevent memory leaks in Node.js?
Memory leaks occur when objects that are no longer logically needed remain reachable and therefore cannot be garbage-collected. Common causes include unbounded caches, forgotten event listeners, timers, global references, retained closures, and collections that continuously grow. Prevention involves controlled lifecycles, bounded caches, removing listeners, clearing timers, and using heap snapshots and profiling when investigating leaks.
Key Takeaways
- Leaks occur when unnecessary objects remain reachable.
- Watch caches, listeners, timers, globals, and retained closures.
- Heap snapshots can help identify retained objects.
Knowledge Check
Which can cause a Node.js memory leak?