Node.js, Evented I/O, and a Cup of Tea

All Arthur Dent really wanted was a cup of tea.

I was reading The Restaurant at the End of the Universe by Douglas Adams, and I found a humorous example of event driven programming. So I thought I would share.

The Story

Arthur Dent was one of the last surviving humans after Earth had been destroyed to make way for a new hyperspace bypass. He was living on a spaceship known as the “Heart of Gold,” which onboard had an amazing piece of equipment called the “Nutri-Matic Drinks Synthesizer” which “claimed to produce the widest possible range of drinks personally matched to the tastes and metabolism of whoever cared to use it.”

The problem was that “when put to the test, however, it invariably produced a plastic cup filled with a liquid that was almost, but nit quite, entirely unlike tea.” So Arthur tried to reason with the machine with no success. He would ask for tea, and the machine would respond with a cheerful “Share and enjoy” and produce the same sickly liquid.

Finally, after all reason and attempts failed, he tried one last time:

“No,” he said, “look, it’s very, very simple … all I want … is a cup of tea. You are going to make one for me. Keep quiet and listen.”

And he sat. He told the Nutri-Matic about India, he told it about China, he told it about Ceylon. He told it about broad leaves drying in the sun. He told it about silver teapots. He told it about summer afternoons on the lawn. He told it about putting in the milk before the tea so it wouldn’t get scalded. He even told it (briefly) about the history of the East India Company.

“So that’s it, is it?” said the Nutri-Matic when he had finished.

“Yes,” said Arthur, “that is what I want.”

“You want the taste of dried leaves boiled in water?”

“Er, yes. With milk.”

“Squirted out of a cow?”

“Well, in a manner of speaking I suppose …”

“I’m going to need some help with this one,” said the machine tersely. All the cheerful burbling had dropped out of its voice and it now meant business.

“Well, anything I can do,” said Arthur.

“You’ve done quite enough,” the Nutri-Matic informed him.

So everything was grand? Well, not quite. There were two problems.

First, the Nutri-Matic needed help processing all this information. So, it asked the spaceship’s computer to help:

[The Nutri-Matic] summoned up the ship’s computer.

“Hi there!” said the ship’s computer.

The Nutri-Matic explained about tea to the ship’s computer. The computer boggled, linked logic circuits with the Nutri-Matic and together they lapsed into a grim silence.

Arthur watched and waited for a while, but nothing further happened.

He thumped it, but still nothing happened.

Eventually he gave up and wandered up to the bridge.

Now, having the Heart of Gold’s entire computer system help calculate how to generate a cow and grow a tree to produce leaves so Arthur could have his tea isn’t a terrible issue, except the second problem:

A Vogon ship approached and began to attack.

So when the rest of the crew rushed to the bridge, they were perplexed that their entire computer was jammed, and all of their controls, navigation, and weapons were unresponsive. However, the reason was soon discovered:

“What have you done to it, Monkeyman?” he breathed.

“Well,” said Arthur, “nothing in fact. It’s just that I think a short while ago it was trying to work out how to …”

“Yes?”

“Make me some tea.”

“That’s right guys,” the computer sang out suddenly, “just coping with that problem right now, and wow, it’s a biggy. Be with you in a while.” It lapsed back into a silence that was only matched for sheer intensity by the silence of the three people staring at Arthur Dent.

As if to relieve the tension, the Vogons chose that moment to start firing.

Don’t worry, fortunately the occupants of the ship were able to hold a seance, summon the great grandfather of the captain, and have the great grandfather’s spirit save them. (I know, such an awesome book)

Anyway, that is a long example, but it show a point:

Evented I/O

Basically Evented I/O is when your program does some sort of I/O (like querying a database, reading a file, etc) and continues on executing, not waiting (or blocking) for the response. So in our example above, the ship can be seen like a PHP script:

<?php

$ship = new HeartOfGold();
$nutrimatic = new NutriMatic();

$recipe = $ship->processQuery('How to make tea.');
$nutrimatic->makeDrink($recipe);

$enemies = $ship->detectEnemies();
if($enemies)
{
    $ship->evasiveManuvers();
}

The problem is the ship can’t detect enemies until it finishes processing Arther’s request on how to make tea. Now, in Node.js, you have functions that are callbacks. It is a way to say “Hey, when this request is done, do this afterwards.”

var ship = new HeartOfGold();
var nutrimatic = new NutriMatic();

ship.processQuery('How to make tea.', function(recipe){ 
   nutrimatic.makeDrink(recipe);
});

var enemies = ship.detectEnemies();
if(enemies.length > 0)
{
    ship.evasiveManuvers();
}

Now the function processQuery is non-blocking, meaning it will start the process of learning how to make tea and create a recipe, but continue execution. That way if it detects enemies, it can perform evasiveManuvers().

In a real life example, processQuery could be querying a database with a very slow query. In PHP, you can’t continue executing your code until that result is returned. However, in Node.js, if your SQL library takes advantage of Node.js’s evented abilities, you can send off a query and continue executing, and when the query returns you can do additional logic through your callback.

Hopefully that makes sense. I like finding programming analogies in books, especially with Douglas Adam’s series of Hitchhiker’s Guide to the Galaxy, since they are so fun to read.

Justin is currently the Director of Development for the Deseret News. He is active in the Utah Open Source community. He is an advisory member of the Utah Open Source Foundation, and helps with the anual Utah Open Source Conference. He primarily focuses on PHP, MySQL, Redis, HTML, CSS, jQuery, and JavaScript. When he gets the time, he enjoys to play jazz piano. Read More

Tagged with: , , ,
Posted in Programming