Advertisement
karlakmkj

Node.js - events module

Oct 8th, 2021
1,204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Here we require in the 'events' module and save a reference to it in an events variable
  2. let events = require('events');
  3.  
  4. // function which expects 'data' to be passed and will log a string to the console which incorporates that data
  5. let listenerCallback = (data) => {
  6.     console.log('Celebrate ' + data);
  7. }
  8.  
  9. // Create an instance of the EventEmitter class
  10. let myEmitter = new events.EventEmitter();
  11.  
  12. // .on() method takes the name of the event (as a string) as its first argument & the listener callback function as its second argument
  13. myEmitter.on('celebration', listenerCallback);
  14.  
  15. // .emit() method which announces a named event has occurred. Takes name of the event as its first argument & a string of your choice as the second argument
  16. myEmitter.emit('celebration', 'good times, come on! Here we go!');
  17.  
  18. // Run program by typing node app.js onto the terminal
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement