search
HomeWeb Front-endJS TutorialAn in-depth analysis of the events module in nodejs

This article will introduce you to the events module in node in detail. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

An in-depth analysis of the events module in nodejs

Related recommendations: "nodejs Tutorial"

The events module is the core module of node, and almost all commonly used node modules inherit it Events modules, such as http, fs, etc. This article will introduce the event mechanism in nodeJS in detail

EventEmitter

Most Node.js core APIs adopt an idiomatic asynchronous event-driven architecture, in which certain types of objects (called triggers) The named event will be triggered periodically to call the function object (listener). For example, a net.Server object will trigger an event every time there is a new connection; an fs.ReadStream will trigger an event when a file is opened; a stream will trigger an event when the data is readable.

【EventEmitter】

The EventEmitter class is defined and opened by the events module. All objects that can trigger events are instances of the EventEmitter class

var EventEmitter = require('events');
/*
{ [Function: EventEmitter]
  EventEmitter: [Circular],
  usingDomains: false,
  defaultMaxListeners: [Getter/Setter],
  init: [Function],
  listenerCount: [Function] }
 */
console.log(EventEmitter);

The EventEmitter attribute of the events module points to The module itself

var events = require('events');
console.log(events.EventEmitter === events);//true

EventEmitter is a constructor that can be used to generate an instance of the event generator emitter

var EventEmitter = require('events');
var emitter = new EventEmitter();
/*
EventEmitter {
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined }
 */
console.log(emitter);

Method

[emitter.emit(eventName[, .. .args])】

eventName <any>
...args <any></any></any>

This method synchronously calls each listener registered to the event named eventName in the order in which the listeners are registered, and passes in the provided parameters. If the event has a listener, it returns true, otherwise it returns false

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('test1',function(){});
console.log(emitter.emit('test1'));//true
console.log(emitter.emit('test2'));//false

[emitter.on(eventName, listener)]

This method is used to add the listener function to the event named eventName. The end of the listener array

eventName <any> 事件名
listener <function> 回调函数</function></any>

 [Note] Will not check whether the listener has been added. Calling multiple times and passing in the same eventName and listener will cause the listener to be added and called multiple times

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('test',function(){
    console.log(1);
});
emitter.on('test',function(){
    console.log(2);
});
emitter.emit('test');//1 2

This method returns an EventEmitter reference, which can be called in a chain

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('test',function(){
    console.log(1);
}).on('test',function(){
    console.log(2);
});
emitter.emit('test');//1 2

[emitter.addListener( eventName, listener)】

Alias ​​of emitter.on(eventName, listener)

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.addListener('test',function(){
    console.log(1);
});
emitter.emit('test');//1

【emitter.prependListener()】

Different from the on() method, prependListener( ) method can be used to add an event listener to the beginning of the listener array

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('test',function(){
    console.log(1);
}).prependListener('test',function(){
    console.log(2);
});
emitter.emit('test');//2 1

[emitter.once(eventName, listener)]

This method adds a one-time listener function to the eventName event. The next time the eventName event is triggered, the listener will be removed, and then

eventName <any> 事件名
listener <function> 回调函数</function></any>
var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('test',function(){
    console.log(1);
}).once('test',function(){
    console.log(2);
});
emitter.emit('test');//1 2
emitter.emit('test');//1

[emitter.prependOnceListener()]

is called. This method is used to add the event listener to the beginning of the listener array. . The next time the eventName event is triggered, the listener will be removed, and then call

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('test',function(){
    console.log(1);
}).prependOnceListener('test',function(){
    console.log(2);
});
emitter.emit('test');//2 1
emitter.emit('test');//1

[emitter.removeAllListeners([eventName])]

eventName <any></any>

to remove all or the listeners of the specified eventName. Returns an EventEmitter reference, which can be called in a chain

[Note] It is a bad practice to remove listeners added elsewhere in the code, especially when the EventEmitter instance is another component or module (such as socket or file stream)

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('test',function(){
    console.log(1);
}).removeAllListeners('test');
emitter.emit('test');//''

【emitter.removeListener(eventName, listener)】

eventName <any>
listener <function></function></any>

Removes the specified listener from the listener array of the event named eventName

var EventEmitter = require('events');
var emitter = new EventEmitter();
function show(){
    console.log(1);
}
emitter.on('test',show).removeListener('test',show);
emitter.emit('test');//''

[Note] removeListener will only remove at most one listener instance from the listener array. If any single listener is added multiple times to the listener array for a specified eventName, removeListener must be called multiple times to remove each instance

var EventEmitter = require('events');
var emitter = new EventEmitter();
function show(){
    console.log(1);
}
emitter.on('test',show).on('test',show).removeListener('test',show);
emitter.emit('test');//'1'

 [Note] Once an event is triggered, all bindings The listeners to it will be triggered in order. This means that any call to removeListener() or removeAllListeners() after the event fires but before the last listener has finished executing will not remove them from emit() . Subsequent events will occur as expected. Because listeners are managed using internal arrays, calling this will change the position index of any listeners registered after the listener has been removed. Although this does not affect the order in which the listeners are called, it means that the copy of the listener array returned by the emitter.listeners() method needs to be recreated

var EventEmitter = require('events');
var emitter = new EventEmitter();
function show1(){
    console.log(1);
    emitter.removeListener('test',show2);
}
function show2(){
    console.log(2);
}
emitter.on('test',show1).on('test',show2);
emitter.emit('test');//1 2
emitter.emit('test');//1

Settings

[emitter.eventNames( )】

Returns an array listing the events for which the trigger has registered listeners. The value in the array is a string or symbol

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.addListener('test1',function(){console.log(1);});
emitter.addListener('test2',function(){console.log(2);});
console.log(emitter.eventNames());//[ 'test1', 'test2' ]

[emitter.listenerCount(eventName)]

eventName <any> 正在被监听的事件名</any>

Returns the number of listeners that are listening to the event named eventName

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.addListener('test',function(){console.log(1);});
emitter.addListener('test',function(){console.log(1);});
console.log(emitter.listenerCount('test'));//2

【emitter.listeners(eventName)】

eventName <any></any>

Returns a copy of the listener array for the event named eventName

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.addListener('test',function(){console.log(1);});
emitter.addListener('test',function(){console.log(2);});
console.log(emitter.listeners('test'));//[ [Function], [Function] ]emitter.listeners('test')[0]();//1

【emitter.getMaxListeners()】

Returns EventEmitter The current maximum listener limit value

var EventEmitter = require('events');
var emitter = new EventEmitter();
console.log(emitter.getMaxListeners());//10

[emitter.setMaxListeners(n)]

  默认情况下,如果为特定事件添加了超过 10 个监听器,则 EventEmitter 会打印一个警告。 此限制有助于寻找内存泄露。 但是,并不是所有的事件都要被限为 10 个。 emitter.setMaxListeners() 方法允许修改指定的 EventEmitter 实例的限制。 值设为 Infinity(或 0)表明不限制监听器的数量。返回一个 EventEmitter 引用,可以链式调用

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){});
/*
Warning: Possible EventEmitter memory leak detected. 11 a listeners added. Use emitter.setMaxListeners() to increase limit
 */
var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.setMaxListeners(11);
emitter.on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){});

【EventEmitter.defaultMaxListeners】
  每个事件默认可以注册最多10个监听器。单个EventEmitter实例的限制可以使用emitter.setMaxListeners(n)方法改变。所有EventEmitter实例的默认值可以使用EventEmitter.defaultMaxListeners属性改变

  [注意]设置 EventEmitter.defaultMaxListeners 要谨慎,因为会影响所有EventEmitter 实例,包括之前创建的。因而,调用 emitter.setMaxListeners(n) 优先于 EventEmitter.defaultMaxListeners

var EventEmitter = require('events');var emitter = new EventEmitter();
EventEmitter.defaultMaxListeners = 11;
emitter.on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){});

事件

【'newListener' 事件】

eventName <any> 要监听的事件的名称
listener <function> 事件的句柄函数</function></any>

  EventEmitter 实例会在一个监听器被添加到其内部监听器数组之前触发自身的 'newListener' 事件

  注册了 'newListener' 事件的监听器会传入事件名与被添加的监听器的引用。事实上,在添加监听器之前触发事件有一个微妙但重要的副作用: 'newListener' 回调中任何额外的被注册到相同名称的监听器会在监听器被添加之前被插入 

var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('newListener',function(){
    console.log(2);
})
emitter.on('test',function(){
    console.log(1);
})

emitter.emit('test');//2 1
var EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('test',function(){
    console.log(1);
})
emitter.on('newListener',function(){
    console.log(2);
})
emitter.emit('test');//1

【'removeListener' 事件】

eventName <any> 事件名
listener <function> 事件句柄函数</function></any>

  'removeListener' 事件在 listener 被移除后触发

var EventEmitter = require('events');
var emitter = new EventEmitter();
function show(){
    console.log(1);
}
emitter.on('removeListener',function(){
    console.log(2);//2})
emitter.on('test',show).removeListener('test',show);
var EventEmitter = require('events');
var emitter = new EventEmitter();
function show(){
    console.log(1);
}
emitter.on('test',show).removeListener('test',show);
emitter.on('removeListener',function(){
    console.log(2);//''})
var EventEmitter = require('events');
var emitter = new EventEmitter();
function show(){
    console.log(1);
}
emitter.removeListener('test',show);
emitter.on('removeListener',function(){
    console.log(2);//''})

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of An in-depth analysis of the events module in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools