Skip to content

Instantly share code, notes, and snippets.

@laverdet
Created January 22, 2011 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laverdet/791157 to your computer and use it in GitHub Desktop.
Save laverdet/791157 to your computer and use it in GitHub Desktop.
node-fibers adapter example
$ cat adapter.js
require('./node-fibers');
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 = [].slice.call(arguments, 1);
var fiber = Fiber.current;
function cb(err, ret) {
if (err) {
fiber.throwInto(new Error(err));
} else {
fiber.run(ret);
}
}
// 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.open, fs.write, fs.close) but we can
// use them as if they're synchronous.
print('opening /tmp/hello\n');
var file = asyncAsSync(fs.open, '/tmp/hello', 'w');
var buffer = new Buffer(5);
buffer.write('hello');
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');
}).run();
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