I'm a bit confused about the difference between on()
and addListener()
in Node.js events. any explanation that clarifies the differences?
Asked
Active
Viewed 3,694 times
9
-
2Why is this tagged [tag:web] when it seems to have nothing to do with any kind of web and the tag says "DO NOT USE"? – Quentin Feb 06 '19 at 16:03
3 Answers
9
There is no difference
The documentation lists .on
and .addListener
as an alias
One thing that I'll point out is in the documentation it does state that .on
returns an Event Emitter, whereas addListener
does not specifically state this.
This is just an oversight, and in fact if you type the code out it's easy to see:
const EventEmitter = require("events");
const myEE = new EventEmitter();
let a = myEE.on("foo",()=>{});
let b = myEE.addListener("foo",()=>{});
console.log(a);
console.log(b);
Both these logs will print the same thing, and you'll see something analogous to the following:
EventEmitter {
domain: Domain {
domain: null,
_events: { error: [ Function: debugDomainError ] },
_eventsCunt: 1,
_maxListeners: undefined,
members: []
},
_events: { foo: [ [ Function ], [ Function ] ] },
_eventsCount: 1,
_maxListeners: undefined
}
So no. There are no differences between them.

zfrisch
- 8,474
- 1
- 22
- 34
3
on
is an alias for addEventListener
https://nodejs.org/docs/latest/api/events.html#events_emitter_addlistener_eventname_listener

Brandon
- 1,747
- 2
- 13
- 22
2
As per documentation, they are just aliases, so there is no difference.
See also how they are defined in the lib.

vsemozhebuty
- 12,992
- 1
- 26
- 26