यदि आप एसिंक कॉलबैक में डेटा को संरक्षित करना चाहते हैं और वहां परिदृश्य हो सकते हैं, जहां अनुरोध और प्रतिक्रिया ऑब्जेक्ट उपलब्ध नहीं हैं। तो उस मामले में continuation-local-storage पैकेज, सहायक है।
इसका उपयोग किसी बिंदु से डेटा या वर्तमान एक्सप्रेस अनुरोध/प्रतिक्रिया तक पहुंचने के लिए किया जाता है जहां यह आसानी से सुलभ नहीं होता है। यह नेमस्पेस की अवधारणा का उपयोग करता है।
यहाँ कैसे मैं इस
की स्थापना continuation-local-storage
पैकेज
npm install continuation-local-storage --save
नाम स्थान
let app = express();
let cls = require('continuation-local-storage');
let namespace = cls.createNamespace('com.domain');
बनाएं स्थापित करें तो मिडलवेयर है
app.use((req, res, next) => {
var namespace = cls.getNamespace('com.domain');
// 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() {
// set data on the namespace, makes it available for all continuations
namespace.set('data', "any_data");
next();
});
})
किसी भी फाइल में
अब या कार्य करते हैं तो आप इस नाम स्थान मिलता है और यह
//logger.ts
var getNamespace = require("continuation-local-storage").getNamespace;
let namespace = getNamespace("com.domain");
let data = namespace.get("data");
console.log("data : ", data);
स्रोत
2017-11-30 12:05:19
दरअसल में सहेजे गए डेटा का उपयोग कर सकते हैं, और यह एक आम मुहावरा है - उदाहरण के लिए (http [मार्ग मिडिलवेयर पर एक्सप्रेस डॉक्स] की जाँच : //expressjs.com/guide.html#route-middleware)। –