minimal Zone implementation for Node
This implementation is based on the experimental async_hooks
API, but it seems to work fine.
Work with any asynchronous tasks (IO, timers, promises, external modules, …).
Warning: Don't work correctly with sync/async generator functions.
Zones are a way to pass contextual data through the call stack without the need to pass them explicitely via arguments.
They are useful in a number of cases, a few example:
- passing a logger
- passing a user record, for instance for checking permissions in an API implementation
- passing a lang or theme preference, in case of a UI
Installation of the npm package:
> npm install --save node-zone
import { current } from "node-zone";
// a zone has a name, a parent, and data
console.log(
current.name, // "<root>"
current.parent, // null
current.data // { __proto__: null }
);
// create a new child zone
const myZone = current.fork("my zone");
console.log(
myZone.name, // "my zone"
myZone.parent, // current
myZone.data // { __proto__: current.data }
);
// run some code in it
myZone.run(() => {
console.log(current.name); // "my zone"
// zone is preserved in async functions
process.nextTick(() => {
console.log(current.name); // "my zone"
});
});
console.log(current.name); // "<root>"
Note: There is an issue with Node cluster module, which prevents handlers created in workers to properly access the current zone,
Zone.current
will be the root zone instead.
If you are using Bluebird promises, you need to enable async_hooks
support:
Bluebird.config({
asyncHooks: true,
});
Source: Bluebird documentation.
Contributions are very welcomed, either on the documentation or on the code.
You may:
- report any issue you've encountered;
- fork and create a pull request.
ISC © Julien Fontanet