diagnostics_channel Publishes Telemetry
A diagnostics channel publishes named telemetry that any module can subscribe to, decoupling instrumentation from the code that emits requests.
Code
// diagnostics_channel publishes named events; any module can subscribe
// without importing the publisher.
import { channel } from 'node:diagnostics_channel';
interface RequestTelemetry {
id: string;
status: number;
}
const requests = channel('app:http-request');
const delivered: string[] = [];
const onMessage = (message: unknown, name: string | symbol) => {
const telemetry = message as RequestTelemetry;
delivered.push(`${String(name)} ${telemetry.id} ${telemetry.status}`);
};
requests.subscribe(onMessage);
requests.publish({ id: 'req-1', status: 200 } satisfies RequestTelemetry);
requests.publish({ id: 'req-2', status: 500 } satisfies RequestTelemetry);
requests.unsubscribe(onMessage);
requests.publish({ id: 'req-3', status: 200 } satisfies RequestTelemetry);
console.log('delivered:', delivered.join(' | '));
console.log('subscribers after unsubscribe:', requests.hasSubscribers);Output
Captured from a sandboxed run of this snippet in the build pipeline.
delivered: app:http-request req-1 200 | app:http-request req-2 500
subscribers after unsubscribe: falseHow the snippet works
diagnostics_channel Publishes Telemetry is built around the function onMessage.
channel comes from node:diagnostics_channel — Node.js core modules the runtime ships with.
What to watch for
- The only import,
node:diagnostics_channel, is part of the Node.js standard library.
Applying it
The entry-point signature is const onMessage = (message: unknown, name: string | symbol)
The demo output is labeled (delivered:, subscribers after unsubscribe:); each label names the call that printed it.
Statements that matter
requests.publish({ id: 'req-1', status: 200 } satisfies RequestTelemetry);
requests.publish({ id: 'req-2', status: 500 } satisfies RequestTelemetry);
requests.publish({ id: 'req-3', status: 200 } satisfies RequestTelemetry);
Interactive Tools for This Topic
FAQ
- Is the imported module an npm package?
- No — `node:diagnostics_channel` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.
Report a problem with this exampleOpens a pre-filled issue on GitHub.