Node.js Course
Node.js
/
Intermediate

EventEmitter

Definition

The core class in Node.js that facilitates event-driven programming. It allows objects to emit named events that cause previously registered 'listener' functions to execute.

Explain Like I'm New

It's a digital megaphone. You hand the megaphone to an object. When something important happens, the object yells into the megaphone (emits an event). Anyone in your code who is 'listening' to that specific yell will immediately run their code.

Real World Example

The `fs.createReadStream()` function returns an EventEmitter. When it reads a chunk of a file, it yells `'data'`. When it finishes reading the entire file, it yells `'end'`. You listen to these events to know when to update your UI.

Common Use Cases

  • •Handling asynchronous streams
  • •Decoupling complex logic
  • •Building custom publisher/subscriber systems

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What method is used to trigger an event?

intermediate

  • What is the difference between `.on()` and `.once()`?

Flash Cards

Question

What method is used to trigger?

Click to reveal answer
Answer

`.emit('eventName', payload)`

Question

Difference between .on() and .once()?

Click to reveal answer
Answer

`.on()` listens forever. If the event fires 100 times, the callback runs 100 times. `.once()` listens only for the VERY FIRST time the event fires, runs its callback, and then automatically unregisters itself so it never runs again.