Created
September 26, 2013 08:34
-
-
Save othiym23/6711428 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dns = require('dns') | |
, namespaces | |
; | |
function Namespace () { | |
// every namespace has a default / "global" context | |
this.active = Object.create(null); | |
this._stack = []; | |
this.id = null; | |
} | |
Namespace.prototype.enter = function (context) { | |
this._stack.push(this.active); | |
this.active = context; | |
}; | |
Namespace.prototype.exit = function (context) { | |
// Fast path for most exits that are at the top of the stack | |
if (this.active === context) { | |
this.active = this._stack.pop(); | |
return; | |
} | |
// Fast search in the stack using lastIndexOf | |
var index = this._stack.lastIndexOf(context); | |
this.active = this._stack[index - 1]; | |
this._stack.length = index - 1; | |
}; | |
function create(name) { | |
var namespace = new Namespace(name); | |
namespace.id = process.addAsyncListener( | |
function () { | |
return namespace.active; | |
}, | |
{ | |
before : function (context) { namespace.enter(context); }, | |
after : function (context) { namespace.exit(context); } | |
} | |
); | |
namespaces[name] = namespace; | |
return namespace; | |
} | |
namespaces = process.namespaces = Object.create(null); | |
create("__test"); | |
function postToCollector() { | |
dns.lookup('nodejs.org', function (error, address) { | |
console.log(address); | |
}); | |
} | |
process.nextTick(postToCollector); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment