Node.js Async Hook Abstraction

1.7.6 · active · verified Tue Apr 21

async-hook-jl is a Node.js library that provides a high-level, stable abstraction over Node.js's internal, currently undocumented `AsyncWrap` API. It enables developers to inspect and hook into the lifecycle of "handle objects" (internal resources like network connections, timers, etc.) within the Node.js runtime. This includes events like initialization (`init`), pre-execution (`pre`), post-execution (`post`), and destruction (`destroy`) of asynchronous operations. The library aims to address some inconsistencies in the native `AsyncWrap` API, offer a more uniform interface, and crucially, allow multiple hooks to be registered simultaneously. The current stable version is 1.7.6, with recent updates focusing on compatibility and minor fixes rather than new features. Its primary differentiator is making a powerful, low-level internal Node.js API accessible and more robust for userland modules, with the long-term hope that similar functionality will eventually be integrated directly into Node.js core.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `async-hook-jl`, register all four types of lifecycle hooks (`init`, `pre`, `post`, `destroy`), enable them, and observe their output during a simple `setTimeout` operation.

const asyncHook = require('async-hook-jl');

function init(uid, handle, provider, parentUid, parentHandle) {
  console.log(`[INIT] UID: ${uid}, Provider: ${asyncHook.providers[provider]}, Parent UID: ${parentUid}`);
}
function pre(uid, handle) {
  console.log(`[PRE] UID: ${uid}`);
}
function post(uid, handle, didThrow) {
  console.log(`[POST] UID: ${uid}, DidThrow: ${didThrow}`);
}
function destroy(uid) {
  console.log(`[DESTROY] UID: ${uid}`);
}

// Add the defined hooks
asyncHook.addHooks({ init, pre, post, destroy });

// Enable the hooks globally
asyncHook.enable();

// Demonstrate an asynchronous operation
console.log('Starting timer...');
setTimeout(() => {
  console.log('Timer finished after 100ms.');
}, 100);

// Optional: Disable after some time or specific operations
// setTimeout(() => {
//   asyncHook.disable();
//   console.log('Async hooks disabled.');
// }, 500);

view raw JSON →