Would EventEmitter cause memory leak if removeAllListeners() is not called?

This question came into my head when I was working with node-imap module. (See https://github.com/mscdex/node-imap)

In this module, the fetch() method would call a callback function that gives it an ImapFetch() object, which your code is suppose to listen on for a 'message' event. The message event in turns passes a message object for each object with events that you need to listen on.

Here's the sample code from the module:

imap.fetch(results,
  { headers: ['from', 'to', 'subject', 'date'],
    cb: function(fetch) {
      fetch.on('message', function(msg) {
        console.log('Saw message no. ' + msg.seqno);
        msg.on('headers', function(hdrs) {
          console.log('Headers for no. ' + msg.seqno + ': ' + show(hdrs));
        });
        msg.on('end', function() {
          console.log('Finished message no. ' + msg.seqno);
        });
      });
    }
  }, function(err) {
    if (err) throw err;
    console.log('Done fetching all messages!');
    imap.logout();
  }
);

As shown, the listeners are never removed. This might be fine if the process quits right after it runs once. However, if the process is long running, the code get repeatedly executed, would it cause a memory leak? I.e. since the listeners are never removed, they keep all the fetch and message objects around even though they are only used for the duration of the command.

Is my understanding incorrect?

What happens is that each of your listeners will remain in memory as long as msg remains in memory. This may cause a memory leak if msg lives longer than you intended, by for example still being referenced from somewhere. However, if there are no more references to msg then it will be removed from memory, and the listeners will follow if they have no more references to them either.

You seem to think that the listeners will keep the event emitter around, but it is the other way around.

The example you gave would most likely not cause a memory leak because it looks like msg is disposed by node-imap after it's done with it.