CodexBloom - Programming Q&A Platform

Memory Leak in Node.js with Event Emitters and Promises - Need Help

👀 Views: 29 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
node.js event-emitter promises memory-leak JavaScript

I'm testing a new approach and I'm experiencing a memory leak in my Node.js application that uses event emitters and promises. After a few hours of running, the memory usage spikes significantly, and I suspect it might be related to how I'm handling listeners and asynchronous operations. I'm using Node.js v14.17.0 and have implemented an event emitter to trigger some background jobs. Here's a simplified version of my code: ```javascript const EventEmitter = require('events'); const { promisify } = require('util'); class JobEmitter extends EventEmitter {} const jobEmitter = new JobEmitter(); const performJob = async (jobId) => { return new Promise((resolve) => { setTimeout(() => { console.log(`Job ${jobId} completed`); resolve(); }, 1000); }); }; const startJob = async (jobId) => { jobEmitter.emit('jobStarted', jobId); await performJob(jobId); }; jobEmitter.on('jobStarted', (jobId) => { console.log(`Starting job ${jobId}`); }); setInterval(() => { startJob(Date.now()); }, 500); ``` This code creates a new job every 500ms and listens for the 'jobStarted' event. Over time, I notice the memory keeps increasing, and using tools like `node --inspect` doesn't reveal any obvious leaks. I also tried using `process.memoryUsage()` to log memory stats, and I see a steady increase without any drop. I've attempted to remove listeners when a job completes by adding `jobEmitter.removeListener('jobStarted', ...)`, but it didn't help. Could the way I'm using promises with event emitters be causing the leak? Any suggestions on how to diagnose or resolve this issue would be greatly appreciated! Cheers for any assistance!