### Understanding Nested cls-hooked Contexts and Asynchronous Behavior Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md This example demonstrates the behavior of nested `cls-hooked` contexts created with `namespace.run()`. It shows how values are scoped within each nested context, how `process.nextTick` preserves the current context, and how `setTimeout` (and other timer functions) can revert to the default context if not explicitly run within a namespace. ```javascript var createNamespace = require('cls-hooked').createNamespace; var writer = createNamespace('writer'); writer.run(function () { writer.set('value', 0); requestHandler(); }); function requestHandler() { writer.run(function(outer) { // writer.get('value') returns 0 // outer.value is 0 writer.set('value', 1); // writer.get('value') returns 1 // outer.value is 1 process.nextTick(function() { // writer.get('value') returns 1 // outer.value is 1 writer.run(function(inner) { // writer.get('value') returns 1 // outer.value is 1 // inner.value is 1 writer.set('value', 2); // writer.get('value') returns 2 // outer.value is 1 // inner.value is 2 }); }); }); setTimeout(function() { // runs with the default context, because nested contexts have ended console.log(writer.get('value')); // prints 0 }, 1000); } ``` -------------------------------- ### Creating and Binding a New CLS Context Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md Illustrates how to use `namespace.createContext()` with `namespace.bind()` to ensure a fresh continuation context is used at the time of function invocation, rather than at the time of binding. This is useful for scenarios where context needs to be isolated per invocation. ```JavaScript function doSomething(p) { console.log("%s = %s", p, ns.get(p)); } function bindLater(callback) { return writer.bind(callback, writer.createContext()); } setInterval(function () { var bound = bindLater(doSomething); bound('test'); }, 100); ``` -------------------------------- ### Setting Contextual Data with cls-hooked Namespace Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md This JavaScript snippet demonstrates how to initialize a `cls-hooked` namespace and set a value within it. It shows a common pattern where a user object fetched from a database is stored in the `session` namespace, making it accessible throughout the current continuation chain. ```javascript // setup.js var createNamespace = require('cls-hooked').createNamespace; var session = createNamespace('my session'); var db = require('./lib/db.js'); function start(options, next) { db.fetchUserById(options.id, function (error, user) { if (error) return next(error); session.set('user', user); next(); }); } ``` -------------------------------- ### Create a New CLS Namespace Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md Creates a new continuation-local storage namespace. Each application should create its own namespace to manage continuation-local values, preventing interference with other parts of the application. ```APIDOC cls.createNamespace(name) return: {Namespace} ``` -------------------------------- ### CLS Namespace Class API Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md The `Namespace` class groups values local to functions originating from callbacks passed to `namespace.run()` or `namespace.bind()`. It provides methods for managing continuation contexts and their associated values. ```APIDOC Class: Namespace Application-specific namespaces group values local to the set of functions whose calls originate from a callback passed to `namespace.run()` or `namespace.bind()`. namespace.active return: the currently active context on a namespace namespace.set(key, value) return: `value` Set a value on the current continuation context. Must be set within an active continuation chain started with `namespace.run()` or `namespace.bind()`. namespace.get(key) return: the requested value, or `undefined` Look up a value on the current continuation context. Recursively searches from the innermost to outermost nested continuation context for a value associated with a given key. Must be set within an active continuation chain started with `namespace.run()` or `namespace.bind()`. namespace.run(callback) return: the context associated with that callback Create a new context on which values can be set or read. Run all the functions that are called (either directly, or indirectly through asynchronous functions that take callbacks themselves) from the provided callback within the scope of that namespace. The new context is passed as an argument to the callback when it's called. namespace.runAndReturn(callback) return: the return value of the callback Create a new context on which values can be set or read. Run all the functions that are called (either directly, or indirectly through asynchronous functions that take callbacks themselves) from the provided callback within the scope of that namespace. The new context is passed as an argument to the callback when it's called. Same as `namespace.run()` but returns the return value of the callback rather than the context. namespace.bind(callback, [context]) return: a callback wrapped up in a context closure Bind a function to the specified namespace. Works analogously to `Function.bind()` or `domain.bind()`. If context is omitted, it will default to the currently active context in the namespace, or create a new context if none is currently defined. namespace.bindEmitter(emitter) Bind an EventEmitter to a namespace. Operates similarly to `domain.add`, with a less generic name and the additional caveat that unlike domains, namespaces never implicitly bind EventEmitters to themselves when they're created within the context of an active namespace. namespace.createContext() return: a context cloned from the currently active context ``` -------------------------------- ### Retrieve an Existing CLS Namespace Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md Looks up and returns an existing continuation-local storage namespace by its name. ```APIDOC cls.getNamespace(name) return: {Namespace} ``` -------------------------------- ### Retrieving Contextual Data from cls-hooked Namespace Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md This JavaScript snippet illustrates how to retrieve a value previously set in a `cls-hooked` namespace. It demonstrates fetching the 'user' object from the 'my session' namespace, which was set earlier in the same continuation, to be used for rendering a response. ```javascript // send_response.js var getNamespace = require('cls-hooked').getNamespace; var session = getNamespace('my session'); var render = require('./lib/render.js') function finish(response) { var user = session.get('user'); render({user: user}).pipe(response); } ``` -------------------------------- ### CLS Context Object Definition Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md Describes the `context` object in `cls-hooked`. A context is a plain JavaScript object that is created using its enclosing context as its prototype, forming a chain for value lookup. ```APIDOC context A context is a plain object created using the enclosing context as its prototype. ``` -------------------------------- ### Dispose of a CLS Namespace Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md Disposes of an existing continuation-local storage namespace. Users must ensure all references to the destroyed namespace are removed from their code, as associated contexts will no longer propagate. ```APIDOC cls.destroyNamespace(name) ``` -------------------------------- ### Binding EventEmitter to CLS Namespace Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md Demonstrates how to bind an `EventEmitter` (like `http.IncomingMessage` or `http.ServerResponse` in Express/Connect) to a CLS namespace. This ensures that continuation-local context is propagated correctly across asynchronous operations within HTTP request handling. ```JavaScript http.createServer(function (req, res) { writer.bindEmitter(req); writer.bindEmitter(res); // do other stuff, some of which is asynchronous }); ``` -------------------------------- ### Reset All CLS Namespaces Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md Completely resets all continuation-local storage namespaces. While this stops value propagation, existing references to namespaces in code will still be reachable, so manual cleanup of references is required. ```APIDOC cls.reset() ``` -------------------------------- ### Access Active CLS Namespaces Source: https://github.com/jeff-lewis/cls-hooked/blob/master/README.md Provides access to a dictionary of currently active `Namespace` objects. This property is available only after the `cls-hooked` module has been loaded, allowing library code to conditionally use CLS. ```APIDOC process.namespaces return: dictionary of {Namespace} objects ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.