Generator based flow-control goodness for nodejs (and soon the browser), using
thunks or promises, letting you write non-blocking code in a nice-ish
way.
Currently you must use the --harmony or --harmony-generators flags when
running node 0.11.x to get access to generators.
Co is careful to relay any errors that occur back to the generator, including those
within the thunk, or from the thunk's callback. "Uncaught" exceptions in the generator are
then either passed co()'s thunk or thrown.
While co supports promises, you may return "thunks" from your functions,
which otherwise behaves just like the traditional node-style callback
with a signature of: (err, result).
For example take fs.readFile, we all know the signature is:
fs.readFile(path, encoding,function(err,result){
});
To work with Co we need a function to return another function of
the same signature:
fs.readFile(path, encoding)(function(err,result){
});
Which basically looks like this:
functionread(path,encoding){
returnfunction(cb){
fs.readFile(path, encoding, cb);
}
}
This is what the co.wrap(fn) utility function does for you.
API
co(fn)
Pass a generator fn which is immediately invoked. Any yield expressions
within must return a "thunk", at which point co() will defer execution.
var co =require('co');
var fs =require('fs');
functionread(file){
returnfunction(fn){
fs.readFile(file,'utf8', fn);
}
}
co(function*(){
var a =yieldread('.gitignore');
var b =yieldread('Makefile');
var c =yieldread('package.json');
console.log(a);
console.log(b);
console.log(c);
});
Nesting co() calls
The co() function itself returns a thunk, this means you can nest appropriately:
var co =require('co');
var fs =require('fs');
functionsize(file){
returnfunction(fn){
fs.stat(file,function(err,stat){
if(err)returnfn(err);
fn(null,stat.size);
});
}
}
var foo =co(function*(){
var a =yieldsize('.gitignore');
var b =yieldsize('Makefile');
var c =yieldsize('package.json');
return[a, b, c];
})
var bar =co(function*(){
var a =yieldsize('examples/parallel.js');
var b =yieldsize('examples/nested.js');
var c =yieldsize('examples/simple.js');
return[a, b, c];
})
co(function*(){
var a =yield foo;
var b =yield bar;
console.log(a);
console.log(b);
});
Or a variation of the same thing:
var co =require('co');
var fs =require('fs');
functionsize(file){
returnfunction(fn){
fs.stat(file,function(err,stat){
if(err)returnfn(err);
fn(null,stat.size);
});
}
}
co(function*(){
var a =yieldco(function*(){
var a =yieldsize('.gitignore');
var b =yieldsize('Makefile');
var c =yieldsize('package.json');
return[a, b, c];
})
var b =yieldco(function*(){
var a =yieldsize('examples/parallel.js');
var b =yieldsize('examples/nested.js');
var c =yieldsize('examples/simple.js');
return[a, b, c];
})
console.log(a);
console.log(b);
});
co() return values
Since co() returns a thunk, you may pass a function to this thunk
to receive the return values from the generator. Any error that occurs
is passed to this (sizes) function.
var co =require('co');
var fs =require('fs');
var read =co.wrap(fs.readFile);
var sizes =co(function*(){
var a =yieldread('.gitignore');
var b =yieldread('Makefile');
var c =yieldread('package.json');
return[a.length,b.length,c.length];
});
sizes(function(err,res){
console.log(res);
});
co.wrap(fn, [ctx])
The co.wrap() utility simply wraps a node-style function to return a thunk.
var co =require('co');
var fs =require('fs');
var read =co.wrap(fs.readFile);
co(function*(){
var a =yieldread('.gitignore');
var b =yieldread('Makefile','ascii');
var c =yieldread('package.json','utf8');
console.log(a);
console.log(b);
console.log(c);
});
Optionally you may pass the fn's receiver as the ctx as shown here:
var co =require('co')
var redis =require('redis')
var db =redis.createClient()
db.set=co.wrap(db.set, db)
db.get=co.wrap(db.get, db)
co(function*(){
yielddb.set('foo','bar')
yielddb.set('bar','baz')
var res =yielddb.get('foo')
console.log('foo -> %s', res);
var res =yielddb.get('bar')
console.log('bar -> %s', res);
})
co.join(fn...)
The co.join() utility function allows you to pass multiple thunks, or an array
of thunks and "join" them all into a single thunk which executes them all concurrently,
instead of in sequence. Note that the resulting array ordering is retained.
var co =require('co');
var join =co.join;
var fs =require('fs');
functionsize(file){
returnfunction(fn){
fs.stat(file,function(err,stat){
if(err)returnfn(err);
fn(null,stat.size);
});
}
}
co(function*(){
var a =size('.gitignore');
var b =size('index.js');
var c =size('Makefile');
var res =yieldjoin(a, b, c);
console.log(res);
// => [ 13, 1687, 129 ]
});
As an alias of join(array) you may simply yield an array:
co(function*(){
var a =size('.gitignore');
var b =size('index.js');
var c =size('Makefile');
var res =yield[a, b, c];
console.log(res);
// => [ 13, 1687, 129 ]
});
FAQ
How does this compare to taskjs?
it's smaller
it's not a scheduler
you can use thunks (functions)
you can use promises
Does it work with streams?
Not out of the box, but if you're willing to fight node a bit you can
wrestle streams into something usable:
co(function*(){
var res =yieldget('http://google.com');
console.log('-> %s',res.status);
var buf;
while(buf =yieldres.read()){
console.log(buf.toString());
}
console.log('done');
})
Performance
On my machine 30,000 sequential stat()s takes an avg of 570ms,
while the same number of sequential stat()s with co() takes
610ms, aka the overhead introduced by generators is extremely negligable.