In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail what is the use of event drivers and EventEmitter classes in Node.js. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Nodejs is a single-process, single-threaded application, but the performance is very high because of the asynchronous execution callback interfaces provided by the V8 engine, through which a large number of concurrency can be handled.
Almost every API in Node.js supports callback functions.
Basically all of Node.js 's 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 watcher exits, each asynchronous event generates an event observer, and the callback function is called if an event occurs.
Event driver
Node.js uses an event-driven model, and when web server receives a request, it closes it, processes it, and then serves the 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 webserver accepts requests all the time 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 trigger a callback function when an event is detected.
Node.js has several 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:
/ / introduce events module var events = require ('events'); / / create eventEmitter object var eventEmitter = new events.EventEmitter ()
The following program binds the event handler:
/ / bind events and event handlers eventEmitter.on ('eventName', eventHandler)
We can trigger the event through the program:
/ / trigger event eventEmitter.emit ('eventName'); instance
Create the index.js file with the following code:
/ / introduce fs module var fs = require ("fs"); / / introduce events module var events = require ('events'); / / create object var ee = new events.EventEmitter (); / / bind events and event handlers 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 ("read error:" + err);} else {console.log ("read success:" + data); / / trigger res event ee.emit (' res',data);}})
Next, let's execute the above code:
EventEmitter class
The events module provides only one object: events.EventEmitter. The core of EventEmitter is the encapsulation of event triggers and event listeners.
You can access the module through require ("events");.
/ / introduce events module var events = require ('events'); / / create eventEmitter object var eventEmitter = new events.EventEmitter ()
The error event is triggered if an error occurs when the EventEmitter object is instantiated. The newListener event is triggered when a new listener is added, and the removeListener event is triggered when the listener is removed.
Let's use a simple example to illustrate the use of EventEmitter:
/ / event.js file var EventEmitter = require ('events'). EventEmitter; var event = new EventEmitter (); event.on (' some_event', function () {console.log ('some_event event trigger');}); setTimeout (function () {event.emit ('some_event');}, 1000)
The implementation results are as follows:
Run this code, and the console outputs' some_event event trigger 'after 1 second. The principle is that the event object registers a listener for the event some_event, and then we send the event some_event to the event object after 1000 milliseconds through setTimeout, at which point some_event 's listener is called.
$node event.js some_event event trigger
Each event in EventEmitter consists of an event name and several parameters, and the event name is a string that usually expresses a certain semantics. For each event, EventEmitter supports several event listeners.
When an event is triggered, the event listeners registered to the event are called in turn, and the event parameters are passed as callback function parameters.
Let's explain this process with the following example:
/ / event.js file 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 parameter', 'arg2 parameter')
Execute the above code, and the result is as follows:
$node event.js listener1 arg1 parameter arg2 parameter listener2 arg1 parameter arg2 parameter
In the above example, emitter registers two event listeners for the event someEvent and then triggers the someEvent event.
In the running result, you can see that the callback functions of the two event listeners have been called successively. This is the simplest use of EventEmitter.
EventEmitter provides several properties, such as on and emit. The on function is used to bind the event function, and the emit property is used to trigger an event.
This is the end of this article on "what is the use of event drivers and EventEmitter classes in Node.js". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.