Node.js: Code Outside the Browser / Node.js Internals and How it Works

Events and Event-Driven Architecture

Core idea: Node's built-in modules (http, fs, timers) run on an event-driven model with two roles:

  • πŸ“€ Emitter β€” an object that fires a named event when something happens (a request comes in, a timer ends, a file finishes reading)

  • πŸ‘‚ Listener β€” a callback you attach ahead of time, which runs when that event fires

🌐 Example: HTTP server as an emitter

const server = http.createServer();

server.on('request', (req, res) => {
  console.log('Request received');
  res.end('Request received');
});

Walking through it:

  1. πŸ‘‚ server.on('request', callback) registers a listener for 'request'.

  2. πŸ“€ Every incoming request makes the server emit a 'request' event.

  3. βœ… Because a listener is already attached, the callback runs and responds to the client.

Why this works: πŸ’‘ server is an instance of Node's EventEmitter class β€” it inherits emitting and listening behavior from there.


πŸ‘€ This is the Observer Pattern

EventEmitter is Node's implementation of the Observer Pattern:

  • πŸ‘‚ The observer (listener) waits.

  • πŸ“€ The subject (emitter) eventually fires the event it's waiting for.

  • ⚑ Code reacts to events instead of being called directly β€” the reverse of a normal function call.


🎯 Why it's useful

  • πŸ”— Decoupling β€” modules don't call each other's functions directly. fs doesn't need to know anything about http; each module just emits its own events, and any other code can listen and react.

  • πŸ‘₯ One event, many reactions β€” attach several listeners to the same event with no extra wiring.


βœ… Takeaway

πŸ“€ Emitter fires an event β†’ πŸ‘‚ listener reacts with a callback. πŸš€ This pattern is foundational across Node's core API, and the next lecture puts it into practice directly with EventEmitter.