Table of Contents
Instance" >Instance
##EventEmitter Class
Home Web Front-end JS Tutorial Let's talk about event drivers and EventEmitter class in Node.js

Let's talk about event drivers and EventEmitter class in Node.js

Nov 18, 2021 pm 06:57 PM
node.js event

This article will take you to understand the events in Node, and talk about the event driver and EventEmitter class. I hope it will be helpful to everyone!

Let's talk about event drivers and EventEmitter class in Node.js

Nodejs is a single-process, single-threaded application, but because of the asynchronous execution callback interfaces provided by the V8 engine, a large amount of concurrency can be processed through these interfaces. So the performance is very high.

Almost every API in Node.js supports callback functions.

Node.js Basically all event mechanisms are implemented using the observer pattern in the design pattern.

Node.js single thread is similar to entering a while(true) event loop until no event observer exits. Each asynchronous event generates an event observer. If an event occurs, the callback function is called.


Event-driven program

Node.js uses the event-driven model. When the web server receives a request, it closes it, processes it, and then serves it. Next web request.

When the request is completed, it is put back into the processing queue, and when the beginning of the queue is reached, the result is returned to the user.

This model is very efficient and scalable because the webserver always accepts requests without waiting for any read or write operations. (This is also called non-blocking IO or event-driven IO)

In the event-driven model, a main loop is generated to listen for events, and a callback function is triggered when an event is detected.

Node.js has multiple built-in events. We can bind and listen to events by introducing the events module and instantiating the EventEmitter class, as shown in the following example:

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

The following program binds Event handler:

// 绑定事件及事件的处理程序
eventEmitter.on('eventName', eventHandler);
Copy after login

We can trigger events through the program:

// 触发事件
eventEmitter.emit('eventName');
Copy after login

Create index.js file, The code looks like this:

//引入 fs 模块
var fs = require("fs");

// 引入 events 模块
var events = require('events');

// 创建对象
var ee = new events.EventEmitter();

// 绑定事件及事件的处理程序
ee.on('res', function (data) {
    console.log('res-1');
    console.log(data);
});
ee.on('res', function () {
    console.log('res-2');
});

fs.readFile('hello.txt',{flag:'r',encoding:'utf-8'},function(err,data){
    if(err){
        console.log("读取出错:"+err);
    }else{
        console.log("读取成功:"+data);
        // 触发res事件
        ee.emit('res',data);
    }
})
Copy after login

Next let us execute the above code:

Lets talk about event drivers and EventEmitter class in Node.js

##EventEmitter Class

events The module only provides one object: events.EventEmitter. The core of EventEmitter is the encapsulation of event triggering and event listener functions.

You can access this module through require("events");.

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

EventEmitter object will trigger 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 a listener is removed.

Below we use a simple example to illustrate the usage of EventEmitter:

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

The execution results are as follows:

Run this code, and the console outputs

after 1 second 'some_event event triggers'. The principle is that the event object registers a listener for the event some_event, and then we use setTimeout to send the event some_event to the event object after 1000 milliseconds. At this time, the listener for some_event will be called.

$ node event.js 
some_event 事件触发
Copy after login

EventEmitter Each event consists of an event name and several parameters. The event name is a string, which 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 sequence, and the event parameters are passed as callback function parameters.

Let us explain this process with the following example:

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

Execute the above code, the running results are as follows:

$ node event.js 
listener1 arg1 参数 arg2 参数
listener2 arg1 参数 arg2 参数
Copy after login
In the above example,

emitter Two event listeners were registered for the event someEvent, and then the someEvent event was triggered.

You can see in the running results that two event listener callback functions are called successively. This is the simplest usage of

EventEmitter.

EventEmitter provides several properties such as on and emit. The on function is used to bind the event function, and the emit attribute is used to trigger an event.

For more node-related knowledge, please visit:

nodejs tutorial! !

The above is the detailed content of Let's talk about event drivers and EventEmitter class in Node.js. 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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
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)

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

Event ID 4660: Object deleted [Fix] Event ID 4660: Object deleted [Fix] Jul 03, 2023 am 08:13 AM

Some of our readers encountered event ID4660. They're often not sure what to do, so we explain it in this guide. Event ID 4660 is usually logged when an object is deleted, so we will also explore some practical ways to fix it on your computer. What is event ID4660? Event ID 4660 is related to objects in Active Directory and will be triggered by any of the following factors: Object Deletion – A security event with Event ID 4660 is logged whenever an object is deleted from Active Directory. Manual changes – Event ID 4660 may be generated when a user or administrator manually changes the permissions of an object. This can happen when changing permission settings, modifying access levels, or adding or removing people or groups

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Get upcoming calendar events on your iPhone lock screen Get upcoming calendar events on your iPhone lock screen Dec 01, 2023 pm 02:21 PM

On iPhones running iOS 16 or later, you can display upcoming calendar events directly on the lock screen. Read on to find out how it's done. Thanks to watch face complications, many Apple Watch users are used to being able to glance at their wrist to see the next upcoming calendar event. With the advent of iOS16 and lock screen widgets, you can view the same calendar event information directly on your iPhone without even unlocking the device. The Calendar Lock Screen widget comes in two flavors, allowing you to track the time of the next upcoming event, or use a larger widget that displays event names and their times. To start adding widgets, unlock your iPhone using Face ID or Touch ID, press and hold

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

An article to talk about how to efficiently develop presentation layer Node.js applications An article to talk about how to efficiently develop presentation layer Node.js applications Apr 17, 2023 pm 07:02 PM

How to use Node.js for front-end application development? The following article will introduce you to the method of developing front-end applications in Node, which involves the development of presentation layer applications. The solution I shared today is for simple scenarios, aiming to allow front-end developers to complete some simple server-side development tasks without having to master too much background knowledge and professional knowledge about Node.js, even if they have no coding experience.

See all articles