Creates a disposable scope that binds the given data to any AsyncLocalStorage instances bound to the channel and publishes it to subscribers. The scope automatically restores the previous storage contexts when disposed.
This method enables the use of JavaScript's explicit resource management (using syntax with Symbol.dispose) to manage store contexts without closure wrapping.
import { channel } from 'node:diagnostics_channel';
import { AsyncLocalStorage } from 'node:async_hooks';
const store = new AsyncLocalStorage();
const ch = channel('my-channel');
ch.bindStore(store, (message) => {
return { ...message, timestamp: Date.now() };
});
{
using scope = ch.withStoreScope({ request: 'data' });
// Store is entered, data is published
console.log(store.getStore()); // { request: 'data', timestamp: ... }
}
// Store is automatically restored on scope exit