Node.js Reference ยท Events and Timers
Node.js emitter.prependListener() method
Reference for emitter.prependListener() and prependOnceListener() in Node.js: put a listener first, how ordering works and when it matters.
emitter.prependListener(eventName, listener) works like on(), except that the new listener goes to the front of the list. It will be the first one called the next time the event is emitted. prependOnceListener() does the same for a one-shot listener.
Order matters when listeners depend on each other: for example, a validation step that must run before a handler that writes data, or a logger that must see an event before anything can throw.
emitter.prependListener('request', checkAuth);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
emitter.prependListener(eventName: string | symbol, listener: Function): this emitter.prependOnceListener(eventName: string | symbol, listener: Function): this
| Name | Description |
|---|---|
eventName |
The event to listen for. |
listener |
Function to call, placed before all existing listeners for that event. |
Returns: the emitter.
Errors: ERR_INVALID_ARG_TYPE if listener is not a function.
Usage notes
- Latest prepend wins the front. Prepending A and then B yields the order B, A, followed by the regular listeners.
- Same semantics otherwise. Duplicates are allowed,
'newListener'is emitted before insertion, and the listener-count warning applies. oncevariant.prependOnceListener()removes the listener right before its single call, just likeonce().- Use sparingly. Relying on position makes code fragile, because another module can prepend after you. If order is essential, have one listener call the steps explicitly.
- Stopping propagation. Plain emitters cannot cancel later listeners. A prepended listener can only stop them by throwing, which also aborts the
emit()caller. - Typical uses: logging, metrics, setup that must precede user handlers, and tests that need to observe an event first.
- Removing.
off()removes a prepended listener the same way as any other. - Inspecting.
listeners()returns them in call order, so the first entry runs first.