What is Node.js Zones?

Zone is a library that:

  • Enables more effective debugging by providing better stack traces for asynchronous functions
  • Makes it easier to write and understand asynchronous functions for Node applications
  • Makes it easier to handle errors raised asynchronously and avoid resulting resource leaks
  • Enables you to associate user data with asynchronous control flow

Read the announcement blog and check out an example >>

Dealing with flow control, stack traces and resource leaks

Managing async flow and avoiding callback hell can be accomplished if you develop in a disciplined manner. However, handling errors in async flow in a clean and easy to follow manner can prove very challenging, even for experienced Node developers.

You’ve probably already read about or experimented with a few projects and concepts like domains, promises, trycatch and Brian Ford’s Zone.js. If you aren’t familiar with these projects yet, we’ve written up a comparison.

What’s different about Node.js Zones?

Currently, there are a couple of problems that make it really hard to deal with asynchronous control flow in Node, specifically:

  • Stack traces are useless when an asynchronous function fails
  • Asynchronous functions are hard to compose into more high-level APIs. Imagine implementing a simple asynchronous API like bar(arg1, arg2, cb) where cb is the error-first callback that the user of the API specifies. To implement this correctly you must take care:
    • to always call the callback
    • don’t call the callback more than once
    • don’t synchronously throw and also call the callback
    • don’t call the callback synchronously
  • It is difficult to handle errors that are raised asynchronously. Typically, if Node crashes and the user chooses to ignore the error, resources may leak. In the ideal case it should be easy to handle errors and to avoid resource leaks.
  • Sometimes there is a need to associate user data to an asynchronous flow for example session cookies. Without Zones there isn’t an easy way to do this.

Get started with Zones…


Get the Code

Learn More