Home Web Front-end JS Tutorial Detailed explanation of event processing mechanism in node.js

Detailed explanation of event processing mechanism in node.js

Dec 05, 2016 am 10:59 AM
node.js

EventEmitter Class

In the event module of Node.js, which is used to implement various event processing, an EventEmitter class is defined. All objects that may trigger events are instance objects that integrate a subclass of the EventEmitter class. In Node.js, many methods are defined for the EventEmitter class. All processing related to the binding and unbinding of the object's event processing function is Execution relies on calls to these methods.

Various methods of the EventEmitter class

event: represents the event name

listener: represents the event processing function

The parameters in brackets represent that the parameters are optional parameters

Detailed explanation of event processing mechanism in node.js

on method of the EventEmitter class

var http = require("http");
var server = http.createServer();
server.on("request", function(req, res){
 console.log(req.url);
 res.end();
});
server.listen(1337, "127.0.0.1");
Copy after login

In this code, we specify that when the server receives a client request, output the URL address of the target requested by the client in your console window, and use the end method of the response object to end the response immediately .

Execute the code, and then enter: http://localhost:1337:// in the browser window, the console output is as follows:

Detailed explanation of event processing mechanism in node.js

Console output

Of course, you can also use multiple on methods Executed to bind multiple event handlers to the same event. As follows:

var http = require("http");
var server = http.createServer();
 
server.on('request', function(req, res){
 console.log('接收到客户端请求')
})
 
server.on("request", function(req, res){
 console.log('处理客户端请求')
 console.log(req.url);
 res.end();
})
 
server.on('request', function(req, res){
 console.log('发送响应完毕')
})
 
server.listen(1337, "127.0.0.1");
Copy after login
Copy after login

OK, execute the code, and the console output is as follows:

Detailed explanation of event processing mechanism in node.js

Console output

In addition, by default, up to 10 time processing functions can be bound to the same specified event. You can modify the maximum number of event processing functions that can be bound through the setMaxListeners method. The method is as follows:

emitter.setMaxListeners(n)
Copy after login

once method of the EventEmitter class

The once method of the EventEmiiter class is similar to the on method, and its function is to bind the specified event The difference is that when the event processing function is executed once, it is contacted immediately, that is, the event processing function will only be executed once. The parameters used in the once method are the same as those used in the on method, as follows:

emitter.once(event, listener)
Copy after login

Do an experiment.

Or execute the following code (same as above):

var http = require("http");
var server = http.createServer();
 
server.on('request', function(req, res){
 console.log('接收到客户端请求')
})
 
server.on("request", function(req, res){
 console.log('处理客户端请求')
 console.log(req.url);
 res.end();
})
 
server.on('request', function(req, res){
 console.log('发送响应完毕')
})
 
server.listen(1337, "127.0.0.1");
Copy after login
Copy after login

Then, open 127.0.0.1:1337 twice in a row in the browser window, and the console output is as follows:

Detailed explanation of event processing mechanism in node.js

is displayed twice

Then change the on event to once event, the code is as follows:

var http = require("http");
var server = http.createServer();
 
server.once('request', function(req, res){
 console.log('接收到客户端请求')
})
 
server.on("request", function(req, res){
 console.log('处理客户端请求')
 console.log(req.url);
 res.end();
})
 
server.once('request', function(req, res){
 console.log('发送响应完毕')
})
 
server.listen(1337, "127.0.0.1");
Copy after login

The console output is as follows:

Detailed explanation of event processing mechanism in node.js

The request is processed 2 times, and the rest are only printed once!

Use the removeListener method to cancel the event handler

The code is as follows:

var http = require("http");
var server = http.createServer();
var testFunction = function (req,res) {
 console.log('发送响应完毕')
}
 
server.on('request', function(req, res){
 console.log('接收到客户端请求')
})
 
server.on("request", function(req, res){
 console.log('处理客户端请求')
 console.log(req.url);
 res.end();
})
 
server.on('request', testFunction)
//删除
server.removeListener('request', testFunction)
server.listen(1337, "127.0.0.1");
Copy after login

Run the code, enter 127.0.0.1:1337 in the browser window, the console output is as follows

Detailed explanation of event processing mechanism in node.js

Console output

emit method : Customize the event and trigger it

The code is as follows:

var http = require("http");
var server = http.createServer();
 
server.on("request", function(req, res){
 console.log(req.url);
});
 
//自定义事件
server.on("customEvent", function(arg1, arg2, arg3){
 console.log("自定义事件被触发");
 console.log(arg1);
 console.log(arg2);
 console.log(arg3);
});
 
//触发自定义事件
server.emit('customEvent', '自定义参数1', '自定义参数2', '自定义参数3')
server.listen(1337, "127.0.0.1");
Copy after login

This time, instead of entering the address in the browser window, run the code directly to view the console output. The console output is as follows:

Detailed explanation of event processing mechanism in node.js

Console output

Indicates that we manually triggered the custom event, which is customEvent.

Summary

The above is the entire content of this article. I hope the content of this article can be helpful to everyone learning or using node.js


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

Video Face Swap

Video Face Swap

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

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)

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!

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

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

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.

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

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!

Let's talk about how to use pkg to package Node.js projects into executable files. Let's talk about how to use pkg to package Node.js projects into executable files. Dec 02, 2022 pm 09:06 PM

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

See all articles