Node.js async_hooks Core Module (npm placeholder)

raw JSON →
1.0.0 verified Thu Apr 23 auth: no javascript abandoned

This npm package, `async_hooks` (v1.0.0), is a placeholder that explicitly states it is "squatting for node core module." It provides no functional code or exports. The actual `async_hooks` is a critical Node.js core module, built directly into the Node.js runtime, designed for tracking the lifecycle of asynchronous resources (like promises, timers, and I/O operations) within an application. It enables advanced use cases such as profiling, debugging, and propagating context across asynchronous operations. Historically, parts of this API were marked experimental; however, Node.js now recommends `AsyncLocalStorage` for most asynchronous context tracking, as it offers a more stable, performant, and memory-safe implementation compared to the lower-level `createHook` API. Developers should always directly import `node:async_hooks` as a built-in module and **never** install a package named `async_hooks` from npm, as it is a non-functional squat.

error Error: Cannot find module 'async_hooks'
cause Attempting to import `async_hooks` in an environment where it's not a core module (e.g., browser) or if Node.js cannot resolve the core module due to an incorrectly installed npm package of the same name.
fix
Ensure you are running in a Node.js environment. If you have an async_hooks npm package installed, remove it. Use the explicit node: prefix for imports: import * as async_hooks from 'node:async_hooks';.
error Error [ERR_REQUIRE_ESM]: require() of ES Module not supported.
cause Trying to use `require()` to import `node:async_hooks` (or any other ESM-only module) in a CommonJS module, or trying to `import` in a CommonJS file.
fix
If your project uses CommonJS, use const async_hooks = require('node:async_hooks');. If your project uses ES Modules, use import * as async_hooks from 'node:async_hooks';. Ensure your package.json "type": "module" is set correctly for ESM projects.
breaking Do NOT install the npm package `async_hooks`. It is a non-functional placeholder for a Node.js core module. Installing it will not provide the intended API and may lead to confusion or incorrect builds.
fix Remove `async_hooks` from `package.json` and `node_modules`. Always import the core module directly using `import ... from 'node:async_hooks';` or `require('node:async_hooks');`.
deprecated The `createHook` and `AsyncHook` APIs are generally discouraged for new code in recent Node.js versions (v14+). They have known usability issues, safety risks, and performance implications.
fix For asynchronous context tracking, migrate to the `AsyncLocalStorage` API, which is stable and optimized.
gotcha Calling asynchronous operations like `console.log()` inside `async_hooks` callbacks (e.g., `init`, `before`, `after`, `destroy`) can cause infinite recursion, as these logging operations themselves trigger `async_hooks` events.
fix For debugging within `async_hooks` callbacks, use synchronous logging methods such as `fs.writeSync(1, msg)` to print to stdout without triggering further async events.
npm install async_hooks
yarn add async_hooks
pnpm add async_hooks

Demonstrates `AsyncLocalStorage` for propagating a request ID across asynchronous operations in Node.js.

import { AsyncLocalStorage } from 'node:async_hooks';

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(message: string) {
  const id = asyncLocalStorage.getStore()?.id ?? 'none';
  console.log(`[Request ID: ${id}] ${message}`);
}

function handleRequest(requestId: string, callback: () => void) {
  asyncLocalStorage.run({ id: requestId }, () => {
    logWithId('Starting request processing');
    // Simulate some asynchronous work
    setTimeout(() => {
      logWithId('Intermediate async step');
      callback();
    }, 100);
  });
}

// Simulate incoming requests
console.log('--- Request 1 ---');
handleRequest('req-123', () => {
  logWithId('Request 1 completed');
  console.log('\n--- Request 2 ---');
  handleRequest('req-456', () => {
    logWithId('Request 2 completed');
    console.log('\n--- Request 3 (no ID) ---');
    logWithId('This will show no ID as it is not run within a store.');
  });
});