EventEmitters
We discussed earlier that callbacks are great for the execution of one-off logic. EventEmitters are useful in responding to repeating events. EventEmitters fire events and include the ability to handle these events when triggered. Several important Node APIs are built on EventEmitters.
Events raised by EventEmitters are handled through listeners. A listener is a callback function associated with an event—when the event fires, its associated listener is triggered as well. The event.EventEmitter
is a class that is used to provide a consistent interface to emit (trigger) and bind callbacks to events.
As a common style convention, event names are represented by a camel-cased string; however, any valid string can be used as an event name.
Use require('events')
to access the EventEmitter
class:
var EventEmitter = require('events');
When an EventEmitter instance encounters an error, it emits an error
event. Error events are treated as a special case in Node.js. If you don't handle these...