JsCommunity / node-zone

minimal Zone implementation for Node

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

node-zone

Package Version Build Status PackagePhobia Latest Commit

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.

What are zones and why use them

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

Install

Installation of the npm package:

> npm install --save node-zone

Usage

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.

With Bluebird

If you are using Bluebird promises, you need to enable async_hooks support:

Bluebird.config({
  asyncHooks: true,
});

Source: Bluebird documentation.

Contributions

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.

License

ISC © Julien Fontanet

About

minimal Zone implementation for Node


Languages

Language:JavaScript 100.0%