Skip to content
Related Articles

Related Articles

Improve Article
Async Hooks in Node.js
  • Last Updated : 12 Jun, 2020

Async_hooks module is used because it provides an API to register callbacks tracking the lifetime of asynchronous resources created inside a Node.js application.

Features:

  • You can capture any asynchronous activity in a Node.js process.
  • Minimal performance overhead.
  • Powerful and flexible API.

These resources are tracked in C++ and anything inheriting from the AsyncWrap class is an asynchronous resource.

Life Time Events of Async Resources:

  1. init(asyncId, type, triggerAsyncId, resource): It is called when a class is constructed that has the possibility to emit an asynchronous event. 
    • asyncId: A unique ID for the async resource.
    • type: The type of the async resource.
    • triggerAsyncId: The unique ID of the async resource.
    • resource: Reference to the resource representing the async operation, needs to be released during destroy.
  2. before(asyncId) and after(asyncId):
    • before is called just before registered user callback is executed.
    • after is called immediately after registered user callback is executed.
  3. destroy(asyncId): It is called after the resource corresponding to asyncId is destroyed.




function destroy(id) {
    print({ stage: 'destroy', id })
}
  
const hook = asyncHooks.createHook(
    { init, before, after, destroy })

Output:

{id:2, type:'Timeout', triggerAsyncId:3 }
{id:3, type:'TIMEWRAP', triggerAsyncId:3 }
{stage: 'before', id: 4}
{stage: 'before', id:2}
'User callback fired'
{stage: 'after', id: 2}
{stage: 'after', id:3}
{stage: 'destroy', id: 2}
{stage: 'destroy', id:3}

The API allows listening to low-level async resources from node’s built-in native modules, like fs and net.
Async Hooks High-Level API The fs.stat, fs.read, fs.open, fs.close are represented by a provider and then expose in a way that makes more sense to users and then grouped together into higher-level operations. Basically, if we are tracking our process, seeking CPU usage, memory usage, we are not taking heap snapshots every second, that will kill our server. There we come for asynchronous hooks where we need less detail while servers are running, it makes operation fast and more information.
Note: Node.js would love to expose unwrapped internal timers via async_hooks as well, but currently, they are too expensive. These are also not needed for CLS use cases, but for some extreme use cases, you might want to observe all the async activity, even including internal timers. 
One could imagine a mode for async_hooks that makes these internal resources observable too, and it would be opt-in since it comes with a cost.
 

My Personal Notes arrow_drop_up
Recommended Articles
Page :