node.js is awsome!
The most exhilarating thing about it, is that using JavaScript for asynchronous callbacks on each event makes managing the context of non-blocking responses, wonderfully simple.
check this out:
var sys = require('sys'), fs = require('fs');
function showStats(q)
{
var i = 0, l = q.length, fstat;
while(i < l)
{
fstat = q[i++];
sys.puts(fstat.filename+' - '+fstat.size);
}
}
// these arguments are available to the callback
// due to the closure!
function runStat(fname, q, ql)
{
fs.stat(fname, function(err, stat){
stat.filename = fname;
q.push(stat);
if(q.length == ql)
showStats(q);
});
}
fs.readdir('.', function(err, files){
if(err) throw err;
var q = [];
var i = 0, l = files.length;
while(i < l)
{
runStat(files[i++], q, l);
}
});
This is a simple task script that reads the statistics for each file in a file system, and then when all the results are in, it shows the size of each file in the directory.
By passing the queue object (q) and the total items expected to a function that contains the fs.stat call, and a callback. These values are accessible by the closures of each callback.
This is an incredibly powerful way of coordinating asynchronous events.