Node.js has multiple in-built events available through events module and EventEmitter class which is used to bind events and event listeners. EventEmitter Class As we have seen in the previous section, EventEmitter class lies in the events module. ![]() All objects which emit events are the instances of events.EventEmitter. Whenever an event gets fired, its listener function starts executing. Many objects in a Node emit events, for example, a net.Server emits an event each time a peer connects to it, an fs.readStream emits an event when the file is opened. Event Emitter package (nestjs/event-emitter) provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application.Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. Difference between Events and Callbacks:Īlthough, Events and Callbacks look similar but the differences lies in the fact that callback functions are called when an asynchronous function returns its result where as event handling works on the observer pattern. A component that raises events knows nothing about its clients. There is a main loop in the event driven application that listens for events, and then triggers a callback function when one of those events is detected. An event is like a broadcast, while a callback is like a handshake. It is the one of the reason why Node.js is pretty fast compared to other similar technologies. It means as soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for event to occur. ![]() Node thread keeps an event loop and after the completion of any task, it fires the corresponding event which signals the event listener function to get executed. So it uses async function to maintain the concurrency. As Node.js applications are single threaded and every API of Node js are asynchronous. In Node.js applications, Events and Callbacks concepts are used to provide concurrency.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |