Skip to content

Instantly share code, notes, and snippets.

Created January 22, 2011 14:39
What would you like to do?
node-fibers adapter example
$ cat adapter.js
var print = require('util').print;
// This function runs an asynchronous function from within a fiber as if it
// were synchronous.
function asyncAsSync(fn /* ... */) {
var args = [], 1);
var fiber = Fiber.current;
function cb(err, ret) {
if (err) {
fiber.throwInto(new Error(err));
} else {;
// Little-known JS features: a function's `length` property is the number
// of arguments it takes. Node convention is that the last parameter to
// most asynchronous is a `function callback(err, ret) {}`.
args[fn.length - 1] = cb;
fn.apply(null, args);
return yield();
var fs = require('fs');
var Buffer = require('buffer').Buffer;
Fiber(function() {
// These are all async functions (, fs.write, fs.close) but we can
// use them as if they're synchronous.
print('opening /tmp/hello\n');
var file = asyncAsSync(, '/tmp/hello', 'w');
var buffer = new Buffer(5);
print('writing to file\n');
asyncAsSync(fs.write, file, buffer, 0, buffer.length);
print('closing file\n');
asyncAsSync(fs.close, file);
// This is a synchronous function. But note that while this function is
// running node is totally blocking. Using `asyncAsSync` leaves node
// available to handle more events.
var data = fs.readFileSync('/tmp/hello');
print('file contents: ' +data +'\n');
// Errors made simple using the magic of exceptions
try {
print('deleting /tmp/hello2\n');
asyncAsSync(fs.unlink, '/tmp/hello2');
} catch(e) {
print('caught this exception: ' +e.message +'\n');
// Cleanup :)
print('deleting /tmp/hello\n');
asyncAsSync(fs.unlink, '/tmp/hello');
print('returning control to node event loop\n');
$ ./fiber-shim node adapter.js
opening /tmp/hello
returning control to node event loop
writing to file
closing file
file contents: hello
deleting /tmp/hello2
caught this exception: Error: ENOENT, No such file or directory '/tmp/hello2'
deleting /tmp/hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment