Skip to content

Instantly share code, notes, and snippets.

@othiym23
Created September 26, 2013 08:34
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 othiym23/6711428 to your computer and use it in GitHub Desktop.
Save othiym23/6711428 to your computer and use it in GitHub Desktop.
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