Table of Contents
EventEmitter
Method
[emitter.eventNames( )】
事件
Home Web Front-end JS Tutorial An in-depth analysis of the events module in nodejs

An in-depth analysis of the events module in nodejs

Mar 01, 2021 am 10:41 AM
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);
Copy after login

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

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

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);
Copy after login

Method

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

eventName <any>
...args <any>
Copy after login

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
Copy after login

[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> 回调函数
Copy after login
Copy after login

 [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
Copy after login

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
Copy after login

[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
Copy after login

【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
Copy after login

[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> 回调函数
Copy after login
Copy after login
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
Copy after login

[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
Copy after login

[emitter.removeAllListeners([eventName])]

eventName <any>
Copy after login
Copy after login

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');//''
Copy after login

【emitter.removeListener(eventName, listener)】

eventName <any>
listener 
Copy after login

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');//''
Copy after login

[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'
Copy after login

 [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
Copy after login

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' ]
Copy after login

[emitter.listenerCount(eventName)]

eventName <any> 正在被监听的事件名
Copy after login

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
Copy after login

【emitter.listeners(eventName)】

eventName <any>
Copy after login
Copy after login

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
Copy after login

【emitter.getMaxListeners()】

Returns EventEmitter The current maximum listener limit value

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

[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
 */
Copy after login
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(){});
Copy after login

【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(){});
Copy after login

事件

【'newListener' 事件】

eventName <any> 要监听的事件的名称
listener  事件的句柄函数
Copy after login

  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
Copy after login
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
Copy after login

【'removeListener' 事件】

eventName <any> 事件名
listener  事件句柄函数
Copy after login

  '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);
Copy after login
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);//''})
Copy after login
var EventEmitter = require('events');
var emitter = new EventEmitter();
function show(){
    console.log(1);
}
emitter.removeListener('test',show);
emitter.on('removeListener',function(){
    console.log(2);//''})
Copy after login

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

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles