- [Instructor] A powerful tool that ships
with Node.js is the event emitter.
The event emitter is Node,js' implementation
of the pub-sub design pattern,
and it allows us to create listeners
for and emit custom events.
So let's take a look at it.
We're going to do so in this empty file called app js.
The first thing we'll do is require events here,
and then we're going to create emitter
and set that equal to a new events.EventEmitter.
Perfect.
The next thing we'll do is we're going
to use that pattern that we've seen a lot of.
We'll say emitter.on,
then we will create a custom event
and add a callback function here
that's going to log whoever the message and the user is.
So here we'll say console log,
user
and message.
Excellent, so once we've created this event,
we need to emit this event,
which we'll do with emitter.emit.
We'll use the name of our custom event.
We'll use the same string, customEvent,
and then what we need to pass into this are two things.
We need the message and the user.
So we'll say "hello world,"
and this user here is a computer.
Let's try this again.
We're going to copy and paste this.
We'll replace hello world.
We'll say "that's pretty cool,"
and then the person who said that is Eve.
I said that.
Perfect, so now we can use process.standard input.on.
Whenever there's some new data,
we want to take that data,
and we want to create an input.
We'll say data toString.
We'll trim off any white space.
Now, if the input that's added is exit,
then we're going to emit a custom event
(chuckles) called Goodbye.
That's the message, and the user is the process,
and then we'll call process.exit.
Nice, and then outside of this,
if the input is something else,
we'll say emitter.emit, customEvent.
The message will be data.toString, .trim,
and the user will be the terminal.
I'm also noticing here
I need to add quotes around the terminal.
This is our user.
That should be a string, not a variable.
So let's try to run this.
We'll pop open our terminal.
We'll make sure that we're navigated
to the right directory and run node app.
Our two custom events that we've emitted are found here.
So hello world and that's pretty cool,
and then if I type in anything else,
this is going to be attributed to our terminal user.
So we'll say Node.js is awesome.
Isn't this cool?
Collecting info with custom events.
Perfect, and now if I type exit,
the process says goodbye, and we're jumped out.
The event emitter is a powerful tool
that allows us to decouple logic
and handle asynchronicity in JavaScript.