What is the difference between on() and addListener() in Node.js events?
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.
on
is an alias for addEventListener
https://nodejs.org/docs/latest/api/events.html#events_emitter_addlistener_eventname_listener
As per documentation, they are just aliases, so there is no difference.
See also how they are defined in the lib.