In our interview with Guillermo Rauch on why you should pay attention to Node.js, he explained that one of the uses for Node.js is building Web servers. "JavaScript happens to be a great fit for writing servers due to its event-driven nature," he says. But what exactly does "event-driven" mean and why is it good for writing servers?

Dan York recently wrote a blog post titled "Understanding Event-driven Programming." It's a lucid explanation of event-driven programming based on an analogy given by WebOS/Node.js developer Tim Caswell on York's Herding Code podcast.

Caswell and York use a doctor's office and fast food line as a metaphor for a computing environment. If the fast food joint followed a traditional thread-based model, you'd order your food and wait in line until you received it. The person behind you wouldn't be able to order until your order was done. In an event-driven model, you order your food and then get out of line to wait. Everyone else is then free to order.

Node.js is event-driven, but most Web servers are thread-based. York explains how Node.js works:

  1. You use your web browser to make a request for "/about.html" on a Node.js web server.
  2. The Node server accepts your request and calls a function to retrieve that file from disk.
  3. While the Node server is waiting for the file to be retrieved, it services the next web request.
  4. When the file is retrieved, there is a callback function that is inserted in the Node servers queue.
  5. The Node server executes that function which in this case would render the "/about.html" page and send it back to your web browser.

Considering that it only takes microseconds to serve up the page, what's the big deal? York writes: "microseconds matter! Particularly when you are talking about highly-scalable web servers!"

Please do check out his full explanation.

What do you think of the metaphors?