Gathering detailed insights and metrics for cls-hooked
Gathering detailed insights and metrics for cls-hooked
Gathering detailed insights and metrics for cls-hooked
Gathering detailed insights and metrics for cls-hooked
@types/cls-hooked
TypeScript definitions for cls-hooked
loopback-context
Current context for LoopBack applications, based on cls-hooked
@fastify/request-context
Request-scoped storage support, based on Asynchronous Local Storage, with fallback to cls-hooked for older Node versions
typeorm-transactional-cls-hooked
A Transactional Method Decorator for typeorm that uses cls-hooked to handle and propagate transactions between different repositories and service methods. Inpired by Spring Trasnactional Annotation and Sequelize CLS
cls-hooked : CLS using AsynWrap or async_hooks instead of async-listener for node 4.7+
npm install cls-hooked
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
763 Stars
219 Commits
89 Forks
19 Watching
19 Branches
1 Contributors
Updated on 20 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-0.3%
366,225
Compared to previous day
Last week
3.6%
1,901,845
Compared to previous week
Last month
11.2%
7,818,169
Compared to previous month
Last year
1.1%
85,428,263
Compared to previous year
3
7
Experimental
by Nodejs.AsyncWrap
is unofficial and undocumented but is currently in Nodejs versions 6 & 7cls-hooked
uses AsyncWrap
when run in Node < 8.cls-hooked
uses async_hooks API when run in Node >= 8.2.1Continuation-local storage works like thread-local storage in threaded programming, but is based on chains of Node-style callbacks instead of threads. The standard Node convention of functions calling functions is very similar to something called "continuation-passing style" in functional programming, and the name comes from the way this module allows you to set and get values that are scoped to the lifetime of these chains of function calls.
Suppose you're writing a module that fetches a user and adds it to a session before calling a function passed in by a user to continue execution:
1// setup.js 2 3var createNamespace = require('cls-hooked').createNamespace; 4var session = createNamespace('my session'); 5 6var db = require('./lib/db.js'); 7 8function start(options, next) { 9 db.fetchUserById(options.id, function (error, user) { 10 if (error) return next(error); 11 12 session.set('user', user); 13 14 next(); 15 }); 16}
Later on in the process of turning that user's data into an HTML page, you call another function (maybe defined in another module entirely) that wants to fetch the value you set earlier:
1// send_response.js 2 3var getNamespace = require('cls-hooked').getNamespace; 4var session = getNamespace('my session'); 5 6var render = require('./lib/render.js') 7 8function finish(response) { 9 var user = session.get('user'); 10 render({user: user}).pipe(response); 11}
When you set values in continuation-local storage, those values are accessible
until all functions called from the original function – synchronously or
asynchronously – have finished executing. This includes callbacks passed to
process.nextTick
and the timer functions (setImmediate,
setTimeout, and setInterval), as well as callbacks passed to
asynchronous functions that call native functions (such as those exported from
the fs
, dns
, zlib
and crypto
modules).
A simple rule of thumb is anywhere where you might have set a property on the
request
or response
objects in an HTTP handler, you can (and should) now
use continuation-local storage. This API is designed to allow you extend the
scope of a variable across a sequence of function calls, but with values
specific to each sequence of calls.
Values are grouped into namespaces, created with createNamespace()
. Sets of
function calls are grouped together by calling them within the function passed
to .run()
on the namespace object. Calls to .run()
can be nested, and each
nested context this creates has its own copy of the set of values from the
parent context. When a function is making multiple asynchronous calls, this
allows each child call to get, set, and pass along its own context without
overwriting the parent's.
A simple, annotated example of how this nesting behaves:
1var createNamespace = require('cls-hooked').createNamespace; 2 3var writer = createNamespace('writer'); 4writer.run(function () { 5 writer.set('value', 0); 6 7 requestHandler(); 8}); 9 10function requestHandler() { 11 writer.run(function(outer) { 12 // writer.get('value') returns 0 13 // outer.value is 0 14 writer.set('value', 1); 15 // writer.get('value') returns 1 16 // outer.value is 1 17 process.nextTick(function() { 18 // writer.get('value') returns 1 19 // outer.value is 1 20 writer.run(function(inner) { 21 // writer.get('value') returns 1 22 // outer.value is 1 23 // inner.value is 1 24 writer.set('value', 2); 25 // writer.get('value') returns 2 26 // outer.value is 1 27 // inner.value is 2 28 }); 29 }); 30 }); 31 32 setTimeout(function() { 33 // runs with the default context, because nested contexts have ended 34 console.log(writer.get('value')); // prints 0 35 }, 1000); 36}
Each application wanting to use continuation-local values should create its own namespace. Reading from (or, more significantly, writing to) namespaces that don't belong to you is a faux pas.
Look up an existing namespace.
Dispose of an existing namespace. WARNING: be sure to dispose of any references to destroyed namespaces in your old code, as contexts associated with them will no longer be propagated.
Completely reset all continuation-local storage namespaces. WARNING: while this will stop the propagation of values in any existing namespaces, if there are remaining references to those namespaces in code, the associated storage will still be reachable, even though the associated state is no longer being updated. Make sure you clean up any references to destroyed namespaces yourself.
Continuation-local storage has a performance cost, and so it isn't enabled
until the module is loaded for the first time. Once the module is loaded, the
current set of namespaces is available in process.namespaces
, so library code
that wants to use continuation-local storage only when it's active should test
for the existence of process.namespaces
.
Application-specific namespaces group values local to the set of functions
whose calls originate from a callback passed to namespace.run()
or
namespace.bind()
.
value
Set a value on the current continuation context. Must be set within an active
continuation chain started with namespace.run()
or namespace.bind()
.
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()
.
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.
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.
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.
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.
The most likely time you'd want to use this is when you're using Express or Connect and want to make sure your middleware execution plays nice with CLS, or are doing other things with HTTP listeners:
1http.createServer(function (req, res) { 2 writer.bindEmitter(req); 3 writer.bindEmitter(res); 4 5 // do other stuff, some of which is asynchronous 6});
Use this with namespace.bind()
, if you want to have a fresh context at invocation time,
as opposed to binding time:
1function doSomething(p) { 2 console.log("%s = %s", p, ns.get(p)); 3} 4 5function bindLater(callback) { 6 return writer.bind(callback, writer.createContext()); 7} 8 9setInterval(function () { 10 var bound = bindLater(doSomething); 11 bound('test'); 12}, 100);
A context is a plain object created using the enclosing context as its prototype.
See LICENSE
for the details of the BSD 2-clause "simplified" license used by
continuation-local-storage
. This package was developed in 2012-2013 (and is
maintained now) by Forrest L Norvell, @othiym23,
with considerable help from Timothy Caswell,
@creationix, working for The Node Firm. This
work was underwritten by New Relic for use in their Node.js instrumentation
agent, so maybe give that a look if you have some Node.js
performance-monitoring needs.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 2/28 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
52 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More