What is the purpose of the async_hooks module?

The async_hooks module in Node.js provides an API to track asynchronous resources and their lifecycle. This can be useful for monitoring performance, debugging, or implementing context propagation (such as for logging or tracing). It allows you to track when an asynchronous operation is initiated, completed, or destroyed. Example usage:

const async_hooks = require('async_hooks');

const asyncHook = async_hooks.createHook({
  init(asyncId, type, triggerAsyncId) {
    console.log(`Init: asyncId=${asyncId}, type=${type}, triggerAsyncId=${triggerAsyncId}`);
  },
  before(asyncId) {
    console.log(`Before: asyncId=${asyncId}`);
  },
  after(asyncId) {
    console.log(`After: asyncId=${asyncId}`);
  },
  close(asyncId) {
    console.log(`Close: asyncId=${asyncId}`);
  },
});

asyncHook.enable();