Node.js EventEmitter
All asynchronous I/O operations in Node.js send an event to the event queue when they complete.
Many objects in Node.js dispatch events: a net.Server object dispatches an event each time a new connection is made, and an fs.readStream object dispatches an event every time a file is opened. All of these event-producing objects are instances of events.EventEmitter.
EventEmitter class
The events module provides only one object: events.EventEmitter. The core of EventEmitter is the encapsulation of event triggering and event listener functions.
You can access this module with require("events");.
// Import the events module var events = require('events'); // Create eventEmitter object var eventEmitter = new events.EventEmitter();
An EventEmitter object fires the 'error' event if an error occurs during instantiation. The 'newListener' event is fired when a new listener is added, and the 'removeListener' event is fired when the listener is removed.
Below we use a simple example to illustrate the usage of EventEmitter:
//event.js file var EventEmitter = require('events').EventEmitter; var event = new EventEmitter(); event.on('some_event', function() { console.log('some_event event triggered'); }); setTimeout(function() { event.emit('some_event'); }, 1000);
The execution result is as follows:
Running this code, the console outputs 'some_event event fired' after 1 second . The principle is that the event object registers a listener of the event some_event, and then we send the event some_event to the event object after 1000 milliseconds through setTimeout, and the listener of some_event will be called at this time.
$ node event.js some_event event fires
Each event of EventEmitter consists of an event name and several parameters. The event name is a string that usually expresses certain semantics. For each event, EventEmitter supports several event listeners.
When an event is triggered, the event listeners registered to this event are called in turn, and the event parameters are passed as callback function parameters.
Let us explain the process with the following example:
//event.js file var events = require('events'); var emitter = new events.EventEmitter(); emitter.on('someEvent', function(arg1, arg2) { console.log('listener1', arg1, arg2); }); emitter.on('someEvent', function(arg1, arg2) { console.log('listener2', arg1, arg2); }); emitter.emit('someEvent', 'arg1 parameter', 'arg2 parameter');
Execute the above code, the result of running is as follows:
$ node event.js listener1 arg1 parameter arg2 parameter listener2 arg1 parameter arg2 parameter
In the above example, the emitter registers two event listeners for the event someEvent and then triggers the someEvent event.
In the running result, you can see that the two event listener callback functions are called successively. This is the simplest use of EventEmitter.
From: nodejs rookie tutorial