Skip to content

Instantly share code, notes, and snippets.

@creationix
Forked from taddeiweb/index.js
Created January 27, 2014 21:21
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 creationix/b8eba877adf7db7e9037 to your computer and use it in GitHub Desktop.
Save creationix/b8eba877adf7db7e9037 to your computer and use it in GitHub Desktop.
var http = require('http');
if (!process.addAsyncListener) require('async-listener');
// Setup the process's async listener
process.addAsyncListener(setup, {
before: onBefore
});
var realContext;
var env = {
get context(){
return realContext;
},
set context(value){
throw new Error('please use env.createContext to create a new context')
}
};
var cnt = 0;
env.createContext = function(){
// INIT CONTEXT
realContext = {
'_ctxid': ++cnt
};
};
// Initialize the null context
// This function is called every time the stack is closing
function setup(){
return realContext;
}
// This function is called when the new stack starts
function onBefore(_ , context){
realContext = context;
}
var server = http.createServer(function(req,res){
env.createContext();
req.on('data' , function(){
console.log(env.context);
});
req.on('end', function(){
console.log(env.context);
res.end('ok');
});
});
server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment