Skip to main content

NodeJS CLS

  • Continuation Local Storage - 连续本地存储
  • AsyncLocalStorage - node v12.17+
    • 类似 ThreadLocal
    • getStore, setStore
    • disable
    • enterWith - 当前环境 - AsyncResource 上下文
    • run - callback 内生效
    • exit - callback 内失效
    • AsyncLocalStorage.snapshot
  • AsyncResource
// ALS
// v13.10.0, v12.17.0
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
asyncLocalStorage.run(123, () => {
console.log(`Store: ${asyncLocalStorage.getStore()}`);
setImmediate(() => {
console.log(`setImmediate Store: ${asyncLocalStorage.getStore()}`);
});
});
// node 8+
import { createHook } from 'async_hooks';
const hook = createHook({
init: (asyncId, type, triggerId, resource) => {},
before: (asyncId) => {},
after: (asyncId) => {},
destroy: (asyncId) => {},
});
hook.enable();
  • @fastify/request-context
    • asynchronous-local-storage
    • async_hooks
      • new AsyncResource('fastify-request-context')
    • onRequest - 包装运行环境
      • als.runWith
        • AsyncResource.runInAsyncScope(done,req,raw)
const { als } = require('asynchronous-local-storage');
const requestContext = {
get: als.get,
set: als.set,
};
const cls = require('cls-hooked');
const namespace = cls.createNamespace('my-very-own-namespace');