Events
Explore the role of events in Node.js by understanding the EventEmitter class and how to attach and manage event listeners. Learn to handle synchronous event sequences, use once and on methods, and manage error events to build robust applications.
We'll cover the following...
Event-driven architecture
Most of Node.js is built around an asynchronous, event-driven architecture. Core APIs, such as the fs module or the net, module use events to communicate with the program. Once the fs module is ready to provide data to be read, it net.Server object emits an event.
To handle events, Node.js uses the events module. It has a class named EventEmitter, and all objects that emit events belong to this class. What should the program do once an event is emitted? For this, the eventEmitter.on() function is used. This allows for one or more functions to be attached to a specific event. These attached functions are also called listeners, as they listen for events to be emitted. Furthermore, listener ...