Subscribing, emitting, and removing listeners with events
🎯 Introduction
By the end of this article, you will be able to notify other modules of task results with EventEmitter and manage listeners.
🧱 EventEmitter sends and receives notifications
EventEmitter is Node.js's event notification object. One part of a program emits an event when its work finishes; other parts subscribe beforehand and run their own handlers. For example, a logging feature can record a filename when file processing finishes.
Both sides agree on an event name such as done. It is not an application action Node.js recognizes automatically. Listeners run only when the program explicitly emits the event.
Create events.mjs, prepare the event object, and append subsequent code in order:
import { EventEmitter } from 'node:events'
const bus = new EventEmitter()
bus is the entry point for sending and subscribing to these notifications. Creating it produces no output yet.
👂 on: register who should receive a notification
const log = file => console.log(`Processed: ${file}`)
bus.on('done', log)
on takes an event name and a listener function. This still produces no output because registration is not emission. The function is stored until a future done event.
on returns the event object itself, not the listener's result. You usually do not need this return value when registering a listener.
📣 emit: send a notification with data
bus.emit('done', 'note.txt')
Running the file now prints Processed: note.txt. Values after the event name are passed to listeners, so the file parameter of log receives note.txt.
emit returns whether the event has listeners: true if it does, false otherwise. This says nothing about whether an application task succeeded; it only indicates that a listener exists.
Emitting done again invokes the listener registered with on again, making it suitable for ongoing observation.
🧹 off: remove a listener when it is no longer needed
bus.off('done', log)
bus.emit('done', 'other.txt')
The additional emission produces no log because log has been removed. Pass off the same function reference used during registration. Keep references to listeners you will need to remove, rather than registering anonymous functions you cannot later identify.
When a component, task, or service object is no longer used, remove unnecessary listeners to avoid duplicate processing and retaining unused data.
1️⃣ once: handle only the first notification
Use once when only the first completion matters, regardless of subsequent events:
bus.once('ready', () => console.log('Ready'))
bus.emit('ready')
bus.emit('ready')
This prints Ready once. The listener removes itself when first invoked. It does not receive historical events emitted before registration.
⏱️ emit calls listeners synchronously by default
Append a new event example to the file:
bus.on('check', () => console.log('Listener running'))
bus.emit('check')
console.log('After emission')
This prints Listener running before After emission. emit calls listeners before the next statement, and multiple listeners run in registration order. A slow listener therefore still blocks subsequent JavaScript.
📂 Asynchronous listeners: handle read failures inside the listener
Events suit notifications; the emitting code does not wait for asynchronous listeners to finish. For example, a logging feature notified to read a file reports its own read success or failure.
Create a separate async-events.mjs and prepare the event object and file-reading API:
import { EventEmitter } from 'node:events'
import { readFile } from 'node:fs/promises'
const bus = new EventEmitter()
Register the listener with try/catch inside it:
bus.on('show-file', async file => {
try {
const text = await readFile(file, 'utf8')
console.log('File contents:', text)
} catch (error) {
console.error('Read failed:', error.code)
process.exitCode = 1
}
})
Finally, emit the notification:
bus.emit('show-file', 'note.txt')
console.log('Notification sent')
Create note.txt containing hello in the same directory and run node async-events.mjs. It prints Notification sent first, then File contents: hello. If the file is missing, it prints the notification first, then Read failed: ENOENT, and returns exit code 1 when the program ends.
emit invokes the listener but does not collect and await its returned Promise. A try/catch around bus.emit(...) cannot catch the later read failure. await bus.emit(...) cannot wait for the read either, because emit returns a boolean.
⏳ Await a function directly when the next step needs its result
If you need file contents before continuing, return the read result from a function and await it at the call site. Save this as read-task.mjs:
import { readFile } from 'node:fs/promises'
async function loadText(file) {
return readFile(file, 'utf8')
}
Append the call in the same file:
try {
const text = await loadText('note.txt')
console.log('File contents:', text)
console.log('Read complete; processing can continue')
} catch (error) {
console.error('Read failed:', error.code)
process.exitCode = 1
}
Run node read-task.mjs. If the file exists, it prints the contents followed by Read complete; processing can continue. Otherwise, it reports only the read failure and skips the success branch.
Choose based on the dependency: use events to notify other features to handle work independently; use a function return value and await when the current task needs a result before continuing.
⚠️ error is a special event that needs handling
For an emitter that may report errors, register an error listener before performing the operation:
bus.on('error', error => console.error(error.message))
bus.emit('error', new Error('Read failed'))
This prints Read failed. Emitting error without an error listener causes Node.js to throw, unlike ordinary events that return false when no listeners exist.
The default EventEmitter used here does not automatically turn Promise rejections from async listeners into error events. Catch asynchronous read failures inside the listener as above; registering an error listener alone does not handle all failures.
❓ Questions and answers
Q1: Can I subscribe after an event and still receive it?
A regular EventEmitter does not retain history. Later subscriptions do not receive earlier notifications.
Q2: Why does one emission print multiple times?
Check for duplicate listener registration. on does not deduplicate listeners automatically.
Q3: Can emit retrieve an async listener's result?
No. emit returns whether listeners exist, not their results. Use loadText above and await it at the call site when you need file contents.
🧪 Exercise
Add a once listener, emit the event twice, and compare its output count with an on listener.
// Write your code here
🎉 Try these techniques with your own examples!
