What if your event code could magically run just once without you writing extra checks?
Why Once listeners in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you want to run a piece of code only once when a button is clicked or a file is loaded, but you have to manually track if it already ran.
Manually tracking if an event happened before is tricky and error-prone. You might forget to reset flags or accidentally run the code multiple times, causing bugs or wasted resources.
Once listeners automatically run your code only the first time an event happens, then remove themselves. This keeps your code clean and reliable without extra checks.
let ran = false; eventEmitter.on('data', () => { if (!ran) { ran = true; console.log('Run once'); } });
eventEmitter.once('data', () => { console.log('Run once'); });
You can easily handle one-time events like setup, initialization, or cleanup without extra code to track execution.
When a server starts, you want to log a welcome message only once, no matter how many connections come in. Using a once listener makes this simple and safe.
Manual event tracking is complex and error-prone.
Once listeners run code only once and then remove themselves automatically.
This leads to cleaner, safer, and easier event handling.
Practice
once listener in Node.js event handling?Solution
Step 1: Understand the purpose of once listeners
Once listeners are designed to handle an event only once, meaning they execute their callback a single time.Step 2: Recognize automatic removal behavior
After running once, the listener removes itself automatically to prevent further executions.Final Answer:
It runs only the first time the event is emitted and then removes itself. -> Option BQuick Check:
Once listener = runs once then removes [OK]
- Thinking once listeners run multiple times
- Confusing once with on listeners
- Assuming manual removal is needed
emitter for event 'start'?Solution
Step 1: Identify the correct method for once listeners
The method to add a once listener isonce, noton.Step 2: Check the callback syntax
The callback must be a function, so() => { console.log('Started'); }is correct. Passing the result ofconsole.logdirectly is wrong.Final Answer:
emitter.once('start', () => { console.log('Started'); }); -> Option AQuick Check:
Use emitter.once(event, callback) with a function [OK]
- Using emitter.on instead of emitter.once
- Passing console.log() call instead of function
- Incorrect function syntax in listener
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.once('ping', () => console.log('Ping received'));
emitter.emit('ping');
emitter.emit('ping');What will be the output?
Solution
Step 1: Understand emitter.once behavior
The listener runs only once on the firstemit('ping')call.Step 2: Analyze the two emit calls
The firstemit('ping')triggers the listener and prints 'Ping received'. The second call finds no listener because it was removed after first run.Final Answer:
Ping received -> Option CQuick Check:
once listener runs once, so output once [OK]
- Expecting output on second emit
- Confusing once with on listeners
- Assuming listener stays after first run
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.once('data', console.log('Data event'));
emitter.emit('data');Solution
Step 1: Check how the callback is passed
The code passesconsole.log('Data event')which calls console.log immediately and passes its return (undefined) as listener.Step 2: Understand correct callback usage
The callback should be a function, e.g.,() => console.log('Data event'), to run only on event emit.Final Answer:
The listener callback is called immediately, not on event emit. -> Option AQuick Check:
Pass function, not function call, as listener [OK]
- Calling function instead of passing it
- Assuming event name invalid
- Thinking once method is missing
server. Which code snippet correctly achieves this and prevents multiple logs if the user reconnects?Solution
Step 1: Identify the requirement for single execution
Logging only once means the listener should run once and then remove itself.Step 2: Choose the correct method and callback syntax
server.once('connect', () => console.log('User connected'))uses the once method with a function callback, ensuring single log on first connect.Final Answer:
server.once('connect', () => console.log('User connected')); -> Option DQuick Check:
Use once with function callback for single event handling [OK]
- Using on instead of once for single execution
- Passing function call instead of function
- Expecting multiple logs with once listener
