Latest web development tutorials

Node.js EventEmitter

Node.js all asynchronous I / O operation upon completion will send an event to the event queue.

Node.js which many objects are distributed event: a distributed object net.Server an event every time a new connection, a fs.readStream objects will be issued in the event a file is opened when. All of these objects are generated events events.EventEmitter instance.

EventEmitter class

events module provides only one object: events.EventEmitter. Core EventEmitter is event-triggered and event listener function package.

You can ( "events") by require; to access the module.

// 引入 events 模块
var events = require('events');
// 创建 eventEmitter 对象
var eventEmitter = new events.EventEmitter();

EventEmitter If an error occurs when an object is instantiated, it will trigger the 'error' event. When adding a new listener, 'newListener' event is triggered when the listener is removed, 'removeListener' event is triggered.

Here we use a simple example shows EventEmitter usage:

//event.js 文件
var EventEmitter = require('events').EventEmitter; 
var event = new EventEmitter(); 
event.on('some_event', function() { 
	console.log('some_event 事件触发'); 
setTimeout(function() { 
}, 1000); 

Execution results are as follows:

Run this code, one second after the console output'some_event trigger event'.The principle is that the object is registered event some_event event of a listener, and then we send events some_event by setTimeout 1000 milliseconds after the event in the object, then calls some_event listener.

$ node event.js 
some_event 事件触发

Each event EventEmitter by an event name and a number of parameters, event name is a string, usually expressed certain semantics. For each event, EventEmitter supports several event listener.

When the event occurs, the event to register event listeners are sequentially called as the callback event parameter argument.

Let us take the following example illustrates this process:

//event.js 文件
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 参数', 'arg2 参数'); 

Run the code above, run as follows:

$ node event.js 
listener1 arg1 参数 arg2 参数
listener2 arg1 参数 arg2 参数

The above example, emitter someEvent registered for the event, two event listeners, then triggered someEvent event.

Operating results can be seen in two event listener callback function has been called. This is EventEmitter easiest usage.

EventEmitter provides a number of attributes, such ason and emit.on function is used to bind eventfunction,emit attribute is used to trigger an event. Next we look EventEmitter specific properties described.


No. Method & description
1 addListener (event, listener)
Add a listener for the specified event listener to the end of the array.
2 on (event, listener)
For the specified event to register a listener accepts a string event and a callback function.
server.on('connection', function (stream) {
  console.log('someone connected!');
3 once (event, listener)
Register a single listener for the specified event, that most listeners will trigger once, immediately after releasing the trigger listener.
server.once('connection', function (stream) {
  console.log('Ah, we have our first user!');
4 removeListener (event, listener)
Removes the specified event to a listener, the listener must be the event has registered listeners.
var callback = function(stream) {
  console.log('someone connected!');
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
5 removeAllListeners ([event])
Removes all listeners for all events, if a specified event, remove the specified event for all listeners.
6 setMaxListeners (n)
By default, EventEmitters if you add listeners over 10 will output a warning message. setMaxListeners function is used to increase the number of listeners of the default limits.
7 listeners (event)
Returns an array of listeners for the specified event.
8 emit (event, [arg1], [arg2], [...])
Each listener execution order parameters, if there are registered event listener returns true, otherwise returns false.

Class methods

No. Method & description
1 listenerCount (emitter, event)
Returns the number of listeners for the specified event.


No. Events & Description
1 newListener
  • event - string name of the event

  • listener - the event handling function

The event is triggered when you add a new listener.

2 removeListener
  • event - string name of the event

  • listener - the event handling function

Remove a listener from the specified listener array. Note that this will change in the index is that the listener after listener deleted.


The following examples via connection (connection) event demonstrates EventEmitter class applications.

Create main.js file, as follows:

var events = require('events');
var eventEmitter = new events.EventEmitter();

// 监听器 #1
var listener1 = function listener1() {
   console.log('监听器 listener1 执行。');

// 监听器 #2
var listener2 = function listener2() {
  console.log('监听器 listener2 执行。');

// 绑定 connection 事件,处理函数为 listener1 
eventEmitter.addListener('connection', listener1);

// 绑定 connection 事件,处理函数为 listener2
eventEmitter.on('connection', listener2);

var eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " 个监听器监听连接事件。");

// 处理 connection 事件 

// 移除监绑定的 listener1 函数
eventEmitter.removeListener('connection', listener1);
console.log("listener1 不再受监听。");

// 触发连接事件

eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " 个监听器监听连接事件。");


Code above, execution results are as follows:

$ node main.js
2 个监听器监听连接事件。
监听器 listener1 执行。
监听器 listener2 执行。
listener1 不再受监听。
监听器 listener2 执行。
1 个监听器监听连接事件。

error event

EventEmitter defines a special event error, it contains a semantic error, we would normally trigger an error event in the face of exceptions.

When the error is triggered, EventEmitter stipulate that if no response to a listener, Node.js will use it as an exception, exit the program with an error message.

To target we generally will trigger error event listener settings, avoid the error is encountered throughout the program crashes. E.g:

var events = require('events'); 
var emitter = new events.EventEmitter(); 

Run the following error is displayed:

throw e; // process.nextTick error, or 'error' event on first tick 
Error: Uncaught, unspecified 'error' event. 
at EventEmitter.emit (events.js:50:15) 
at Object.<anonymous> (/home/byvoid/error.js:5:9) 
at Module._compile (module.js:441:26) 
at Object..js (module.js:459:10) 
at Module.load (module.js:348:31) 
at Function._load (module.js:308:12) 
at Array.0 (module.js:479:10) 
at EventEmitter._tickCallback (node.js:192:40) 

Inheritance EventEmitter

Most of the time we do not directly use EventEmitter, but inherited it in the object. Including fs, net, http, including, as long as the support incident response core modules are subclasses of EventEmitter.

Why? There are two reasons:

First, the object has the functionality of a physical realization of events that meet the emission monitor and semantics, the event should be an object.

Second, the object mechanism JavaScript is a prototype-based, multi-part support inheritance, objects EventEmitter not disrupt the original inheritance.