- [Instructor] Let's make some adjustments
to our collectAnswers function.
And the first thing we want to do here
is we want to require the EventEmitter
and we're going to destructure this from the events module.
So I only want to use event emitter.
I don't have to use events.EventEmitter every time.
Once I've imported this,
I can make some adjustments to our function.
The first thing we want to do is include the emitter
which will be a new instance of the EventEmitter.
And we'll call that there.
And then down here at the end of our function,
we want to return the emitter so that we can use it.
So now we can use this emitter to raise events
when certain things happen within this function.
For example, let's say we wanted to raise an event
every time the user answered a question.
What we can do is say emitter.emit
answer with whatever that answer is.
So what we can do now over in our ask function,
we want to be able to respond to these events from the file.
So, because our collect answers function
now returns an EventEmitter,
what we can do is say const answerEvents
set that equal to our collectAnswers function,
and then here, we're going to call answerEvents.on.
So remember we need to refer to the string for the event,
our custom event called answer
and then we need to provide a function
for what to do when this happens.
So we'll take in our answer.
So we'll take in our answer as an argument in console.log.
The answer is answer.
Nice.
Let's try running this we'll type node ask What's your name?
The answer is Eve.
Where do you live?
Tahoe, the answer is Tahoe.
What are you going to do with Node.js?
Save the world.
And now we'll still get all of these done events firing.
We will be able though to have something happen
when we get a new answer.
Modules give us this great way to separate and reuse code.
And the EventEmitter gives us a way
to handle custom events when they are raised.
By using both of these tools together with Readline,
we've created a pretty cool little, no JS module.