Node.js Reference ยท Events and Timers
Node.js emitter.once() method
Reference for emitter.once() in Node.js: run a listener a single time, remove it early with off(), see rawListeners wrappers and use prependOnceListener().
emitter.once(eventName, listener) registers a listener that runs at most one time. The first time the event is emitted, Node removes the listener and then calls it. After that the listener is gone, and later emits do not reach it.
Use it for events that naturally happen once: a connection opening, a server starting to listen, a process becoming ready.
server.once('listening', () => console.log('ready'));
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.once(eventName: string | symbol, listener: (...args: any[]) => void): this emitter.prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this
| Name | Description |
|---|---|
eventName |
The event to wait for. |
listener |
Called with the emitted arguments, at most once. |
Returns: the emitter.
Errors: ERR_INVALID_ARG_TYPE if listener is not a function.
Usage notes
- Removed before it runs. Node removes the one-shot wrapper first and then calls your function, so if the listener itself emits the same event, it does not recurse into itself.
- Wrappers.
listeners()returns your original functions, whilerawListeners()returns the wrapper functions Node actually stores. The wrapper has alistenerproperty pointing to your function. off()takes the original.emitter.off(name, fn)matches both a normal registration offnand aonce()registration of it.- Several once listeners. Each
once()call creates its own wrapper, so registering the same function withonce()twice runs it twice on the first emit, and never again. - Waiting with promises. If you want to
awaitthe next event, useevents.once()instead of wrappingemitter.onceinnew Promiseby hand. It also rejects when'error'is emitted. - Missed events.
once()only sees events emitted after it is registered, exactly likeon(). 'newListener'fires too. Aonce()registration announces the original listener function to any'newListener'handler.- Cleanup in races. When waiting for one of several events, remove the other
once()listeners afterwards or use anAbortSignalwithevents.once().