Events

Learn about Events and the EventEmitter class in Node.js.

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 emitscreates a signal for an event. Whenever a new connection is established, the 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 functions are called synchronously once the object emits a specific event. This makes sure that the sequence of events is preserved and no race conditions or logic errors arise.

Let’s look at the examples below to see how this works.

Get hands-on with 1400+ tech skills courses.