Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use EventEmitter in node.js

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about how to use EventEmitter in node.js. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Events (event trigger)

Events is an event trigger built into nodejs. Events is used in many of the built-in modules of node. For example, http.server triggers events every time it receives a request, and stream uses on to listen for corresponding events based on events. All the objects that trigger events are EventEmitter instances that expose EventEmitter.on ('event', callback), usually registering events with EventTmitte.on and triggering events with EventEmitter.emit.

Example:

Const events= require ('events'); const event=new events () / / instantiate EventEmitterevent.on ('data', (aforb) = > {console.log (' parameter'+ aquib) console.log (this,'this') / / Note: if callback is an arrow function, this points to a global object / / if callback is in the form of function () {}, this will bind to console.log ('emit triggered data event'}) event.emit ('data',1,2) on the EventEmitter instance / / use emit to trigger events

Asynchronous operation

Because the callback in EventEmitter.on ('event name, callback) is executed synchronously, but in some cases we have to use asynchronous operations, so we can use SetImmediate to perform asynchronous operations

Const events= require ('events'); const event=new events (); event.on (' event', (a, b) = > {setImmediate (()) = > {console.log ('this happens asynchronously');}); / / because the listeners here are executed synchronously, but we can use the setImediate function to wait for other content in the listener to finish execution}); event.emit (' event',1,2)

Trigger once

When we normally trigger events through emit, several events in emit will be triggered several times, but we can register events with once, and events triggered by once can only be triggered once.

Const EventEmitter= require ('events'); const MyEventEmitter=new EventEmitter (); let astat0; / / normally register events and trigger MyEventEmitter.on (' add', () = > {averse + console.log (a)}) MyEventEmitter.emit ('add'); / / 1; MyEventEmitter.emit (' add'); / / 2; / / register MyEventEmitter.once using once ('add', () = > {astata + console.log (a)) }) MyEventEmitter.emit ('add') / / 1 MyEventEmitter.emit (' add') / / is not valid

Error event

There is no error event in EventEmitter, so we can only force out execution when an error occurs, so we have to register an error event ourselves so that the error event is triggered when an error occurs

Const EventEmitter=require ('events'); const MyEventEmitter=new EventEmitter (); MyEvenEmitter.on (' error', (err) = > {console.error (err,' misreported')})

In addition to the above method, we can also use errorMonitor to listen for errors triggered by emit without registering error events. With errorMonitor, we no longer need to register error events manually.

Const {EventEmitter,errorMonitor} = require ('events'); const MyEventEmitter=new EventEmitter (); MyEventEmitter.on (errorMonitor, (err) = > {console.log (err);}) MyEventEmitter (' error', new Error ('wrong'))

EventEmitter class

NewListener event

The newListener event is triggered when we add event listeners, so we can register the newListener event to do something when we add event listeners

Const {EventEmitter} = require ('events'); const MyEvent=new EventEmitter () MyEvent.on ('newListener', (name,litener) = > {/ / name is the name of the event being listened for / / listener is the event handler MyEvent.on (' event', () = > {console.log ('events added in newListener')}) MyEvent.on ('event' () = > {console.log ('normally registered event event')}) / / if we no longer trigger the event event The newListener event will be executed, because the newListener event will be triggered as long as we are registering the event / / Note: the newListener event must be registered with EventEmitter.once (), because if we add a registered event to the newListener event, and multiple registered events outside will trigger multiple newListener events, a stack overflow MyEvent.emit ('event') will occur. / / printed results / / events registered with newListener / / normally registered event events

RemoveListener event

The removeListener event is used to delete registered events, but removeListener does not prevent events that are being triggered by emit

Const callbackB= () = > {console.log ('B')} const callbackA= () = > {console.log ('A') event.removeListener ('data',callbackB)} event.on (' data',callbackA) event.on ('data',callbackB) event.emit (' data'); / / data is deleted when callbackA is executed, but the trigger event.emit ('data') of the next emit is not blocked; / / it is actually deleted here.

AddListener and on do the same thing.

EventNames

Returns an array containing the names of all registered events

Const {EventEmitter} = require ('events'); const MyEvent=new EventEmitter (); MyEvent.on (' data', () = > {}); MyEvent.on ('finish', () = > {}); console.log (MyEvent.eventNames ()); / / print result [' data','finish']

GetMaxListeners

Returns the maximum number of events that can be registered. The default is 10. If there are more than 10, there will be a warning, but we can modify it through setMaxListener (20).

Const {EventEmitter} = require ('events'); const MyEvent=new EventEmitter (); console.log (MyEvent.getMaxListener ()); / / 10 event.setMaxListener (20); console.log (MyEvent.getMaxListener (20))

ListenerCount

Returns the number of registered events

Const {EventEmitter} = require ('events'); const MyEvent=new EventEmitter (); MyEvent.on (' data', () = > {}); MyEvent.on ('data', () = > {}); MyEvent.on (' finish', () = {}); console.log (MyEvent.listenerCount ()) / / 2 and above are all the contents of the article "how to use EventEmitter in node.js". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report