Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create an event emitter instance.
Node.js
const EventEmitter = require('events'); const emitter = new [1]();
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong class name like 'Emitter' or 'Event'.
Forgetting to use parentheses to create an instance.
✗ Incorrect
The EventEmitter class is used to create event emitter instances in Node.js.
2fill in blank
mediumComplete the code to add a callback function for the 'data' event.
Node.js
emitter.on('data', [1] => { console.log('Data received:', data); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'function(data)' without arrow syntax here.
Using empty parentheses which means no parameters.
✗ Incorrect
The callback function receives the event data as a parameter. Using data as the parameter name is common and clear.
3fill in blank
hardFix the error in the callback usage by completing the code.
Node.js
function fetchData(callback) {
setTimeout(() => {
const result = 'Hello';
callback([1]);
}, 1000);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the callback function itself instead of data.
Passing unrelated function names.
✗ Incorrect
The callback function should be called with the data result as argument.
4fill in blank
hardFill both blanks to emit an event with a message and listen for it.
Node.js
emitter.[1]('message', 'Hi there!'); emitter.[2]('message', msg => { console.log(msg); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' or 'listen' which are not Node.js EventEmitter methods.
Mixing up 'emit' and 'on' methods.
✗ Incorrect
Use emit to send an event and on to listen for it.
5fill in blank
hardFill all three blanks to decide between callback and event for async handling.
Node.js
function processData(data, [1]) { if (data.length > 5) { [2]('error', new Error('Too long')); } else { [3](null, data); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'emitter.on' instead of 'emitter.emit' to send events.
Confusing callback with event emitter methods.
✗ Incorrect
Use a callback function to handle success or error. Use emitter.emit to send an error event.