Node.js Event Emitters

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


When an event "fires" (which means the same as "publishing an event" or "emitting an event"), each listener will be called synchronously (source), along with any accompanying data that was passed in to emit(), no matter how many arguments you pass in:

myDog.on('bark', (howLoud, howLong, howIntense) => {
  // handle the event
myDog.emit('bark', 'loudly', '5 seconds long', 'fiercely')

The listeners will be called in the order they were registered:

myDog.on('urinate', () => console.log('My first thought was "Oh-no"'))
myDog.on('urinate', () => console.log('My second thought was "Not my lawn :)"'))
// The console.logs will happen in the right order because they were registered in that order.

But if you need a listener to fire first, before all of the other listeners that have already been added, you can use prependListener() like so:

myDog.prependListener('urinate', () => console.log('This happens before my first and second thoughts, even though it was registered after them'))

If you need to listen to an event, but you only want to hear about it once, you can use once instead of on, or prependOnceListener instead of prependListener. After the event is fired and the listener gets called, the listener will automatically be removed, and won't be called again the next time the event is fired.

Finally, if you want to remove all of the listeners and start over, feel free to do just that:


Got any Node.js Question?