What is @types/cls-hooked?
@types/cls-hooked provides TypeScript type definitions for the cls-hooked package, which is used for context propagation across asynchronous calls in Node.js. It allows you to create a context that can be accessed throughout the lifecycle of a request, even across asynchronous boundaries.
What are @types/cls-hooked's main functionalities?
Creating a Namespace
This feature allows you to create a new namespace. A namespace is a context that can be used to store and retrieve data across asynchronous calls.
const cls = require('cls-hooked');
const namespace = cls.createNamespace('myNamespace');
Setting and Getting Context
Within a namespace, you can set and get values that will be available throughout the lifecycle of the asynchronous operations.
namespace.run(() => {
namespace.set('key', 'value');
console.log(namespace.get('key')); // Outputs: value
});
Binding Functions to a Namespace
You can bind functions to a namespace so that they have access to the context set within that namespace.
const boundFunction = namespace.bind(() => {
console.log(namespace.get('key'));
});
namespace.run(() => {
namespace.set('key', 'value');
boundFunction(); // Outputs: value
});
Other packages similar to @types/cls-hooked
async_hooks
The async_hooks module provides an API to track asynchronous resources in Node.js. It is a lower-level API compared to cls-hooked and requires more manual management of context propagation.
continuation-local-storage
This package is similar to cls-hooked and provides a way to maintain context across asynchronous calls. However, it is older and less maintained compared to cls-hooked.
zone.js
zone.js is a library for managing asynchronous context propagation in JavaScript. It is more commonly used in Angular applications but can be used in Node.js as well. It provides a more comprehensive solution for managing asynchronous contexts.