Node.js: Register event waits before starting the producer
A producer can emit its header and completion events in one synchronous call. Awaiting the header before registering a completion wait can miss completion entirely. Register both waits before starting the producer.
Set up
Tested on Debian 13 Linux with Node.js v24.22.1. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as node-register-event-waits-before-start.mjs:
import assert from 'node:assert/strict';
import { EventEmitter, once } from 'node:events';
const producer = new EventEmitter();
const controller = new AbortController();
const options = { signal: controller.signal };
const header = once(producer, 'header', options);
const complete = once(producer, 'complete', options);
const pending = Promise.all([header, complete]);
try {
producer.emit('header', { rows: 2 });
producer.emit('complete', 'report.csv');
const [[metadata], [filename]] = await pending;
assert.equal(metadata.rows, 2);
assert.equal(filename, 'report.csv');
console.log(`header rows: ${metadata.rows}`);
console.log(`complete: ${filename}`);
} finally {
controller.abort();
}
assert.equal(producer.listenerCount('header'), 0);
assert.equal(producer.listenerCount('complete'), 0);
assert.equal(producer.listenerCount('error'), 0);
console.log('remaining listeners: 0');
const failed = new EventEmitter();
const failure = new Error('producer failed');
const failureReport = Promise.all([
once(failed, 'header'),
once(failed, 'complete'),
]);
failed.emit('error', failure);
await assert.rejects(failureReport, (error) => error === failure);
assert.equal(failed.eventNames().length, 0);
console.log('producer error: preserved');Run:
node node-register-event-waits-before-start.mjsObserved output:
header rows: 2
complete: report.csv
remaining listeners: 0
producer error: preservedRead the result
Both promises already have listeners when emission begins. Each resolves to an array of event arguments, which explains the nested destructuring. The first example checks that its event and error listeners are removed. The second verifies that a producer error rejects the combined wait with the original error.
Apply it carefully
This pattern collects the first occurrence of two distinct events; it does not buffer repeated events of one name. Promise.all does not cancel other work. The controller is only for these waits, not for the producer itself. For a real producer that can stall, arrange an external cancellation or deadline and handle its rejection. The controlled emitter here always emits; it tests no network or file operation.
Node documents the multiple-event awaiting caveat and the error and cancellation behavior of events.once.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- node-register-event-waits-before-start.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.