Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Events in NodeJS

Introduction
  1. Node.js is an asynchronous event-driven architecture
  2. All objects that emit events are instances of the EventEmitter class
  3. Event names are camel-cased strings
  4. When the EventEmitter object emits an event, functions attached to that specific event are called synchronously
Implement event
  1. eventEmitter.on() method is used to register listeners
  2. eventEmitter.emit() method is used to trigger the event
const EventEmitter = require('events');
class ShopEmitter extends EventEmitter { }
const cartEmitter = new ShopEmitter();
cartEmitter.on('addItem', function (params) {
    console.log('Item added to cart');
});
let params = { id: 1 };
cartEmitter.emit('addItem', params);
// output
// Item added to cart