Skip to content

Instantly share code, notes, and snippets.

@piscisaureus
Created December 23, 2011 04:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piscisaureus/d50183eb434370cafe6a to your computer and use it in GitHub Desktop.
Save piscisaureus/d50183eb434370cafe6a to your computer and use it in GitHub Desktop.
var d = createDomain(
// The `onyield` function is guaranteed to run always exactly once.
// The only exception is when a parent domain of this domain dies.
// The `onyield` function is ran in the parent domain, e.g. the domain
// that was active at the time the domain was created.
function onyield(err, some, result) {
if (err) return console.log("shit! something fucked up");
console.log("The domain had no errors! It's results were "
+ some + " and " + result);
}
);
// Run some code in the domain
// d.run() must be called from the parent domain.
d.run(function() {
fs.stat('/foo/bar', function(err, stats) {
// Throwing will make the domain die.
if (err) throw err;
var s = fs.createWriteStream("out.bar", "w");
s.write(JSON.stringify(stats), function() {
s.end("the end");
});
s.on('end', function() {
// domain is a global that always points to the current domain
domain.setResult(null, "it", "worked");
});
});
});
var d2 = createDomain(function onyield2(err) {
if (err) console.log(err);
console.log("the end");
});
// Domains will yield after after the number of io handles / nextTicks /
// timers within it drops to zero, but not before at least one piece of code
// has been run in the domain.
d2.run(function() {});
// Because the domain already yielded, this run() call will be ignored.
d2.run(something);
// Streams (and maybe some other classes) have an associated domain. All
// callbacks must be attached from in that domain, and the callbacks will
// also run inside that domain. `createDomain` takes an optional first
// parameter to import a socket into that domain. The socket cannot have
// any callbacks attached at that point.
net.createServer(
function(socket) {
// Valid
console.log(socket.getpeername());
createDomain(socket, function() {
socket.on('data', function(buf) {
console.log(buf.toString());
})
});
}
).listen(8080);
net.createServer(
function(socket) {
// Invalid - will make createDomain throw
socket.on('error', console.log);
// Also invalid - will make createDomain throw
socket.write("bla", afterWrite);
createDomain(socket, function() {
// ...
});
}
).listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment