Typorithm · medium

EventEmitter

event-emitternodejseventslistenerspub-sub
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn EventEmitter

0%

HTTP & Events

EventEmitter from node:events is the pub/sub hub behind Node's async model. on(name, fn) subscribes a listener; emit(name, ...args) fires the event synchronously and passes the arguments to every listener registered for that name.

EventEmitter is the foundation of Node's event-driven design: streams, servers, and processes are all emitters under the hood.

on(name, listener) subscribes — the listener runs every time that named event is emitted, receiving whatever arguments emit passes.

emit(name, ...args) publishes the event synchronously, invoking each listener in registration order with those arguments; decoupling producers from consumers.

01

on subscribes a listener to a named event.

02

emit fires the event and passes arguments to listeners.

03

Listeners run synchronously in registration order.

import { EventEmitter } from "node:events"

const bus = new EventEmitter()

bus.on("data", (x) => {
  console.log("got", x)
})

bus.emit("data", payload)

Read the implementation

Connect each part of the code to the concept before you type.

1. Import EventEmitter

EventEmitter is the built-in class behind Node's event-driven model, exported from node:events.

import { EventEmitter } from "node:events"

2. Create an emitter

A new EventEmitter instance is a hub you can subscribe to and publish events on.

const bus = new EventEmitter()

3. Subscribe with on

on registers a listener that runs every time the named event is emitted.

bus.on("data", (x) => {

4. Publish with emit

emit fires the event synchronously, passing payload to every registered listener.

bus.emit("data", payload)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

EventEmitter: Lesson & Practice · Typorithm | ApplyDjinn