-
-
Save creationix/b8eba877adf7db7e9037 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 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