Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
The zone.js package is a library that implements Zones for JavaScript. Zones are execution contexts that allow you to intercept and keep track of asynchronous operations in JavaScript. This is particularly useful for debugging, performance tracking, and managing multiple tasks in complex applications such as Angular.
Error Handling
Intercepts errors within a specific zone and allows custom error handling.
Zone.current.fork({
name: 'errorHandlingZone',
onHandleError: (parentZoneDelegate, currentZone, targetZone, error) => {
console.error('Error intercepted in zone:', error);
return false;
}
}).run(() => {
throw new Error('Test Error');
});
Execution Context Tracking
Tracks the scheduling and execution of asynchronous tasks, providing insights into the application's asynchronous flow.
Zone.current.fork({
name: 'trackingZone',
onScheduleTask: (delegate, currentZone, targetZone, task) => {
console.log('Task scheduled:', task.source);
return delegate.scheduleTask(targetZone, task);
}
}).run(() => {
setTimeout(() => {
console.log('Timeout callback executed.');
}, 1000);
});
Performance Monitoring
Measures the time taken to execute asynchronous tasks, which can be used for performance analysis.
Zone.current.fork({
name: 'performanceMonitoringZone',
onInvokeTask: (delegate, currentZone, targetZone, task, applyThis, applyArgs) => {
const start = performance.now();
delegate.invokeTask(targetZone, task, applyThis, applyArgs);
const duration = performance.now() - start;
console.log('Task took:', duration, 'ms');
}
}).run(() => {
setTimeout(() => {
console.log('Timeout callback executed.');
}, 1000);
});
async_hooks is a core Node.js module that provides an API to track asynchronous resources. Unlike zone.js, which works in both browser and Node.js environments, async_hooks is specific to Node.js. It offers a lower-level API compared to zone.js and requires more manual handling.
cls-hooked is a Node.js package that uses async_hooks to provide continuation-local storage (CLS). It allows you to set and get context across async operations, similar to how zones work. However, cls-hooked focuses on context propagation rather than the broader range of interception capabilities that zone.js offers.
continuation-local-storage is another Node.js package that provides CLS functionality. It predates cls-hooked and async_hooks, and it uses a different mechanism to track context. It is less performant than cls-hooked and has been largely superseded by it, but it serves a similar purpose to zone.js in terms of context management.
Implements Zones for JavaScript, inspired by Dart.
If you're using zone.js via unpkg please provide a query param
?main=browser
https://unpkg.com/zone.js?main=browser
See the new API here.
A Zone is an execution context that persists across async tasks. You can think of it as thread-local storage for JavaScript VMs.
See this video from ng-conf 2014 for a detailed explanation:
You can run code within a zone with zone.run
.
Tasks scheduled (with setTimeout
, setInterval
, or event listeners) stay within that zone.
Zone.current.fork({}).run(function () {
Zone.current.inTheZone = true;
setTimeout(function () {
console.log('in the zone: ' + !!Zone.current.inTheZone);
}, 0);
});
console.log('in the zone: ' + !!Zone.current.inTheZone);
The above will log:
'in the zone: false'
'in the zone: true'
Note that the function delayed by setTimeout
stays inside the zone.
Zones have a set of hooks that allow you to change the behavior of code running within that zone. To change a zone, you fork it to get a new one.
zone.fork({
beforeTask: function () {
console.log('hi');
}
}).run(function () {
// do stuff
});
Hooks that you don't override when forking a zone are inherited from the existing one.
See the API docs below for more.
To start using Zones, you need to include the zone.js
script in this package onto
your page. This script should appear in the <head>
of your HTML file before any other
scripts, including shims/polyfills.
There are two kinds of examples:
For fully working examples:
python -m SimpleHTTPServer 3000
).http://localhost:3000/example
in your browserBelow are the aforementioned snippets.
var someZone = zone.fork({
afterTask: function () {
console.log('goodbye');
}
});
someZone.fork({
afterTask: function () {
console.log('cya l8r');
}
}).run(function () {
// do stuff
});
// logs: cya l8r
When you fork a zone, you'll often want to control how the parent zone's hook gets called.
Prefixing a hook with $
means that the hook will be passed the
parent zone's hook, and the hook will be expected to return the function to
be invoked rather than be the function itself.
var someZone = zone.fork({
afterTask: function () {
console.log('goodbye');
}
});
someZone.fork({
$afterTask: function (parentOnLeave) {
// return the hook
return function afterTask() {
parentOnLeave();
console.log('cya l8r');
};
}
}).run(function () {
// do stuff
});
// logs: goodbye
// cya l8r
+
and -
SugarMost of the time, you'll want to run a hook before or after the parent's implementation.
You can prefix a hook with -
for running before, and +
for running after.
The above can be written like this:
var someZone = zone.fork({
afterTask: function () {
console.log('goodbye');
}
});
someZone.fork({
'+afterTask': function () {
console.log('cya l8r');
}
}).run(function () {
// do stuff
});
// logs: goodbye
// cya l8r
This frees you from writing boilerplate to compose a new hook.
Zone.js exports a single object: window.zone
.
zone.run
Runs a given function within the zone. Explained above.
zone.bind
Transforms a function to run within the given zone.
zone.fork
var myZone = zone.fork({
onZoneCreated: function () {},
beforeTask: function () {},
afterTask: function () {},
onError: function () {},
enqueueTask: function() {},
dequeueTask: function() {},
setTimeout: function () {},
setInterval: function () {},
alert: function () {},
prompt: function () {},
});
myZone.run(function () {
// woo!
});
Below describes the behavior of each of these hooks.
zone.onZoneCreated
Runs when a zone is forked.
zone.beforeTask
Before a function invoked with zone.run
, this hook runs.
If zone.beforeTask
throws, the function passed to run
will not be invoked.
zone.afterTask
After a function in a zone runs, the afterTask
hook runs.
This hook will run even if the function passed to run
throws.
zone.onError
This hook is called when the function passed to run
or the beforeTask
hook throws.
zone.enqueueTask
This hook is called when a function is registered with the VM.
For instance setTimeout
and addEventListener
.
zone.dequeueTask
This hook is called when a function is unregistered with the VM.
For instance clearTimeout
and removeEventListener
.
zone.setTimeout
, zone.setInterval
, zone.alert
, zone.prompt
These hooks allow you to change the behavior of window.setTimeout
, window.setInterval
, etc.
While in this zone, calls to window.setTimeout
will redirect to zone.setTimeout
.
zone.requestAnimationFrame
, zone.webkitRequestAnimationFrame
, zone.mozRequestAnimationFrame
These hooks allow you to change the behavior of window.requestAnimationFrame()
,
window.webkitRequestAnimationFrame
, and window.mozRequestAnimationFrame
.
By default the wrapCallback is executed in the zone where those methods have been called to avoid growing the stack size on each recursive call.
zone.addEventListener
This hook allows you to intercept calls to EventTarget#addEventListener
.
var clickListenerCount = 0;
zone.fork(
$addEventListener: function(parentAddEventListener) {
return function (type, listener) {
if (type === 'click') clickListenerCount++;
return parentAddEventListener.apply(this, arguments);
};
}
);
zone.run(function() {
myElement.addEventListener('click', listener);
myOtherElement.addEventListener('click', listener);
console.log(clickListenerCount); // 2
});
zone.removeEventListener
This hook allows you to intercept calls to EventTarget#removeEventListener
.
var clickListenerCount = 0;
zone.fork(
$removeEventListener: function(parentRemoveEventListener) {
return function (type, listener) {
if (type === 'click') clickListenerCount--;
return parentRemoveEventListener.apply(this, arguments);
};
}
);
zone.run(function() {
myElement.addEventListener('click', listener);
myElement.removeEventListener('click', listener);
console.log(clickListenerCount); // 0
});
setTimeout
, setInterval
, and addEventListener
work in FF23, IE10, and Chrome.elt.onevent
works in FF23, IE10, but not Chrome. There's a fix in the works though!MIT
FAQs
Zones for JavaScript
The npm package zone.js receives a total of 3,418,332 weekly downloads. As such, zone.js popularity was classified as popular.
We found that zone.js demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.