Let's talk about event drivers and EventEmitter class in Node.js
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!
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();
The following program binds Event handler:
// 绑定事件及事件的处理程序 eventEmitter.on('eventName', eventHandler);
We can trigger events through the program:
// 触发事件 eventEmitter.emit('eventName');
Instance
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); } })
Next let us execute the above code:
##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.
// 引入 events 模块 var events = require('events'); // 创建 eventEmitter 对象 var eventEmitter = new events.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);
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 事件触发
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.
//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 参数');
$ node event.js listener1 arg1 参数 arg2 参数 listener2 arg1 参数 arg2 参数
emitter Two event listeners were registered for the event
someEvent, and then the
someEvent event was triggered.
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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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]](https://img.php.cn/upload/article/000/887/227/168834320512143.png?x-oss-process=image/resize,m_fill,h_207,w_330)
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

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.

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

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!

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

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.
