You've used events before in browser JavaScript — button.addEventListener('click', ...). Node has its own version of the same idea, built around a class called EventEmitter, and a lot of Node's own built-in APIs are built on top of it.
const EventEmitter = require('events')
const emitter = new EventEmitter()on() registers a function to run when a named event happens. emit() triggers it:
emitter.on('greet', (name) => {
console.log(`Hello, ${name}!`)
})
emitter.emit('greet', 'Priya') // logs: Hello, Priya!Any extra arguments passed to emit() get forwarded to every listener. And a single event can have more than one listener — all of them run, in the order they were registered.
const EventEmitter = require('events')
class OrderSystem extends EventEmitter {
placeOrder(item) {
console.log(`Order placed: ${item}`)
this.emit('order-placed', item)
}
}
const orders = new OrderSystem()
orders.on('order-placed', (item) => {
console.log(`Sending confirmation email for: ${item}`)
})
orders.on('order-placed', (item) => {
console.log(`Updating inventory for: ${item}`)
})
orders.placeOrder('Laptop Stand')The placeOrder method doesn't need to know anything about emails or inventory — it just announces that an order happened. Anything that cares can listen for it. New behavior can be added later just by attaching another on() listener, with no changes to placeOrder itself.
This is exactly the shape Node itself uses internally. A file stream emits 'data' as chunks arrive and 'end' when it's done; an HTTP server emits 'request' for every incoming request. Understanding EventEmitter here makes those built-in APIs — covered in the next several lessons — far less mysterious.
An event name is just a string you choose — there's no fixed list. 'order-placed' works because both the emitter and the listener agree to use that exact spelling; a typo in either place means the listener silently never runs.