In Node.js, EventEmitter is an object that facilitates communication/interaction between objects in Node. EventEmitter is at the core of Node’s asynchronous event-driven architecture. It’s used to trigger events and handle the events when they occur.
Here are some steps on how you can use it:
Install Node.js
Before you can use EventEmitter, you need to have Node.js installed on your computer.
Create EventEmitter Instance
To create an EventEmitter instance (object), you need to include the ‘events’ module and call its constructor.
```
const events = require(‘events’);
const eventEmitter = new events.EventEmitter();
```
Define Events
You can define an event using the `on()` function. `on()` function takes two parameters, the event name and the event handler function.
```
eventEmitter.on(‘eventName’, eventHandler);
```
For example:
```
eventEmitter.on(‘greeting’, function() {
console.log(‘Hello World!’);
});
```
Trigger Events
You can trigger an event using the `emit()` function. Here ‘eventName’ should match the name specified in `on()` function.
```
eventEmitter.emit(‘eventName’);
```
For example:
```
eventEmitter.emit(‘greeting’); // Output: Hello World!
```
Handle Event With Parameter
You can also pass parameters to the event handler function.
```
eventEmitter.on(‘greeting’, function(name) {
console.log(`Hello ${name}!`);
});
eventEmitter.emit(‘greeting’, ‘John’); // Output: Hello John!
```
Error Events
Error events are defined with the name “error”. If these events are triggered without being handled (means there isn’t any ‘error’ event defined), Node will stop the program with an exception.
```
const readStream = fs.createReadStream(‘./not-exist.txt’);
readStream.on(‘error’, function(err) {
console.log(`Error: ${err}`);
});
```
It’s important to note that every time an event is emitted, all functions attached to that event are called synchronously. Any values returned by the called listeners are ignored and discarded.
So, EventEmitter provides a powerful way to create custom events and have objects subscribe to those events and react when they’re triggered. This means you get to decide when those events should be triggered by emitting them at appropriate points in your program.