QUESTION:
Is there any way to create a variable storage in per session/http request? The variable must be globally accessible and different
Yes, with some caveats.
You're looking for a module called continuation-local-storage.
This allows you to keep arbitrary data for the remainder of callbacks for the current request, and access it in a global fashion.
I wrote a blog post about it here. But the gist is this:
npm install --save continuation-local-storageCreate a namespace for your app (at the top of the main file for your app)
var createNamespace = require('continuation-local-storage').createNamespace,
namespace = createNamespace('myAppNamespace');
Create a middleware that runs downstream functions in the cls (continuation-local-storage) namespace
var getNamespace = require('continuation-local-storage').getNamespace,
namespace = getNamespace('myAppNamespace'),
app.use(function(req, res, next) {
// wrap the events from request and response
namespace.bindEmitter(req);
namespace.bindEmitter(res);
// run following middleware in the scope of the namespace we created
namespace.run(function() {
namespace.set(‘foo’, 'a string data');
next();
});
});
Since you ran next within namespace.run, any downstream function can access data in the namespace
var getNamespace = require('continuation-local-storage').getNamespace,
namespace = getNamespace('myAppNamespace');
// Some downstream function that doesn't have access to req...
function doSomething() {
var myData = namespace.get('foo');
// myData will be 'a string data'
}
There is the caveat that certain modules can "lose" the context created by cls. This means that when you go to lookup 'foo' on the namespace, it won't have it. There are a few ways to deal with this, namely using another module like cls-redis, cls-q, or binding to the namespace.