Skip to content
Tutorials Center
My learning

Topics

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.

NODE
server.once('listening', () => console.log('ready'));

Try it

Node.js Runs once, then disappears

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.

Node.js Removing a once listener early

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

NODE
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, while rawListeners() returns the wrapper functions Node actually stores. The wrapper has a listener property pointing to your function.
  • off() takes the original. emitter.off(name, fn) matches both a normal registration of fn and a once() registration of it.
  • Several once listeners. Each once() call creates its own wrapper, so registering the same function with once() twice runs it twice on the first emit, and never again.
  • Waiting with promises. If you want to await the next event, use events.once() instead of wrapping emitter.once in new Promise by hand. It also rejects when 'error' is emitted.
  • Missed events. once() only sees events emitted after it is registered, exactly like on().
  • 'newListener' fires too. A once() 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 an AbortSignal with events.once().