Node JS Tutorial for Beginners #8 – The Node Event Emitter

you know something guys welcome to your eighth no js' tutorial and in this video we're going to take a look at the invent module or rather guys so in the last tutorial what we did was we created a custom module called stuff we required that in this app.js file and called that variable stuff and then we used it now as well as creating custom modules nodejs also ships with a bunch of inbuilt core modules which we can use in our application and we can require them in the same way that we would require custom modules okay now one of those core modules in nodejs is called the events module and that's what we're going to take a look at so when we are requiring an a core module what we need to do is just pop in the module name right here not the path to the module or anything like that just the module name and because it's a core module built into nodejs node will recognize that and it will go out and it will fetch that module for us so this module is called events so that's all we need to do and then we better change the name of this variable to something like events as well so now whatever is returned on the module the exports of this module is going to be stored in this events variable now okay now one of the things returned on that module the exports property in this module is the event emitter and we can use the event emitter in nodejs to create custom events and then react to those events when they are emitted so if you've ever used jQuery we have something similar in ours too recently like this elements dot on click fire a function okay this is an event listener right so we're saying okay well when this element fires a click event or emits a click event then we want to fire this callback function and do something ok so we are reacting to an event being emitted on this element so we can do similar thing in know GS we can create our own custom elements instead of things like clique and those sorry we can create custom events instead of things like clique and those events can be whatever you want so let's get rid of this and do a simple example so return tours on this module to exports in the events module like I say is the event emitter and that is a constructor so what we need to do is create a new variable and I'm going to call this my emitter and I'm going to set this equal to a new and then I'm going to use this variable right here events dot invent emitter okay so now we're going to have our own events emitter object stored here so now we can wire up events to this so we can say something like this we can say my emitter sorry dots on and then create an event and we'll just call this event some events something meaningless right and then when this event occurs when it omits then we want to do something and that's going to be in this callback function right here and if we want we can pass through a parameter into this callback function let's just say message okay so when this event occurs when it's emitted what we're going to do is log to the console this message okay so now let's go ahead and emit this event so we'll say my emitter and we can say dot emit and then choose which event to emit so some events and we also pass a parameter through to the callback function so the first argument in this emit function is the event we want to emit and then the arguments thereafter or whatever we pass through into this function so let the message just be and the event was emitted okay so now if we save this and say node up and run it then you should see the event was emitted logged to the console of the terminal and that's because we listened out for this event right here being emitted by saying Dodd some event okay so we're listening for that event now on this thing right here on this object and then what we're doing is manually emitting that event right here and we're passing this data the string into this function and then when this event is emitted this function this callback function is fired and it logs that message to the console okay so let's do another example something a little bit more complicated to better show you the powers of this event emitter so I'm going to delete these things right now and then to demonstrate this next example I'm going to require another core module in nodejs and this other module is called util which is shot for utilities and it's a utilities module which allows us to do various things one of the things that the util module allows us to do is inherit certain things from objects built into nodejs or other objects okay so let's require this and you'll see exactly what I mean in a minute I'm going to say util equals and then require you to okay so we'll use that in a minute but first of all what I'm going to do is create a new object constructor so I'll say var and this is going to be a person and then I'll say this is equal to a function and it's going to take in a name and then inside here we're going to say this dot name is equal to name so whatever we create a new person we need to pass it through a name okay so let's go ahead now and use this util function or util module rather so what I want to do is inherit the events bitter so I want any person that's created using this to inherit the event emitter so we can attach custom events to people so what we'll do is we'll say util which is this thing right here dot inherits and then we pass through two things into this function the first thing we pass through is the object constructor that we want to inherit something and that is person so we want person to inherit will do and the thing we want it to inherit is the events dots event emitter okay so now it's going to inherit this and anything created using this person constructor is going to be able to have custom events attached to it okay so let's go ahead and make some people I'm just going to make three people so first of all I'll say large Ames equals new person and then we pass through the name which is James then I'm going to do two more so I'll just copy this dude right now and paste it down couple of times the second one I'll call Mary and passing the name there as well and the third one let's just call Ryu and we'll pass in the name there as well cool so now we have three people okay James Mary and right so now what I want to do is wire up some event listeners to each one of these using some custom events so I'm going to store these three people in an array first of all and I'll call this array people so set that equal to an array and the first one is going to be James second one is going to be Mary and the third one is going to be right so now they're all stored in an array and now what I can do because they're stored in an array is say people dot for each which is just a JavaScript method which is recycle through each one of these right yeah and then for each one of these we're going to fire this callback function and it's going to take the name of whatever person or the person itself so that's going to be James Mary all right you and inside this function we're going to attach some events or some listeners for events okay so what I'll do is say person dots on and then we'll have speak so we're taking whatever person object is currently being passed through into this callback function so it could be any one of these and we're attaching this listening to it because we can do now we've inherited the event emitter on to any object which is created using this constructor so we can attach custom events to these people now so that's what we're doing we're attaching a custom event to each person as we go through it in the array and then as we attach them what we're going to do is clear a callback function which is going to take in a message something that they say okay so let's go ahead and log something earth something to the console so we'll say console dot blog or say person dot name which is this property right here that we made we pass through when we create those objects so we're going to log the name and then we're going to concatenate set and then we're going to concatenate the message okay so when we emit these speak events on each person then it's going to fire this callback function take through a message then it's going to say who spoke and then the message so let's call some events let's say James dot emit because that's how we emit the events and then it's going to be a speak event and we're going to pass through a message which is going to be hey dudes myself okay so let's save that now and let's run this application so node up and then what we're going to see is say sir James said hey dudes so we attach that event here remember and then we emitted that event right here so we can emit that event on whichever person we make which is in this array which we've attached those events to those listeners so we could say it for bribe and we could say Rome it is going to be a speak event and it's going to be our recruit okay so let's run this again and see what happens this time we get James said hey dudes and Rio said I want a quarry alright so this is really cool we've got custom events now on our own objects which we've made up and we've attached those listeners to each object and then we've admitted those events and we've done that using this events module and the events emitter and the utility module to inherit this event in bitter on our person constructor pretty cool so if you have any questions about this whatsoever feel free to ask those down below otherwise guys I'll see you in the next tutorial

Michael Martin

50 Responses

  1. var fs = require('fs');
    fs.readFile('readMe.txt', 'utf8', function(error, data) {

    fs.writeFile('writeMe.txt', data);
    // It should work but for some reason it does not, can you please tell me WHY!

  2. Very nice tutorial to startup with,
    in this 8th tutorial i found it was not working with me, so i tried for a workaround and it is like

    class Person extends EventEmitter{

    i am using v10.15.1, rest of the things worked fine.

  3. Hi All,

    I am getting below error while executing this example. Can you please help to understand and fix the issue.


    Object.setPrototypeOf(ctor.prototype, superCtor.prototype);


    TypeError: Object.setPrototypeOf called on null or undefined

    at Function.setPrototypeOf (<anonymous>)

    at Object.inherits (util.js:287:10)

    at Object.<anonymous> (C:MyProjectsMyNodeJSProjectsevent-emitterapp.js:16:6)

    at Module._compile (internal/modules/cjs/loader.js:689:30)

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)

    at Module.load (internal/modules/cjs/loader.js:599:32)

    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)

    at Function.Module._load (internal/modules/cjs/loader.js:530:3)

    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)

    at startup (internal/bootstrap/node.js:283:19)

  4. There seems to be quite a few comments which reflect some confusion over the use of events. The best thing to do is to look at the observer pattern where multiple listeners exist for the same event. This should make it more clear. The example could be written like this to illustrate that.

    var events = require('events');
    var Person = function(pname) {
    var name = pname;

    var james = new Person('james');
    var mary = new Person('mary');
    var loudmouth = new Person('blabberer');

    loudmouth.mouth = new events.EventEmitter();

    //jame's observer.
    james.read_lips = function(msg){
    console.log("james found out: " + msg);

    //james adds his event to the emitter's event listener.
    james.enter_elevator = function(){
    console.log('james is in the elevator');
    loudmouth.mouth.on('elevator gossip', james.read_lips)

    //james removes his event from the emitter when he leaves the elevator.
    james.leave_elevator = function(){
    // read lips is how james responds to the event.
    loudmouth.mouth.removeListener('elevator gossip', james.read_lips);
    console.log('james has left the elevator');

    //mary's observer
    mary.overhear = function(msg){
    console.log("mary heard: " + msg);

    //mary adds her observer event to the emitter's event listeners
    mary.enter_elevator = function(){
    // overhear is how mary responds to the event.
    console.log('mary is in the elevator');
    loudmouth.mouth.on('elevator gossip', mary.overhear);

    loudmouth.speaks = function(what_is_said){
    console.log('loudmouth: ' + what_is_said);
    this.mouth.emit('elevator gossip', what_is_said);

    loudmouth.speaks('boss is having an affair');
    loudmouth.speaks('just kidding');

    The console.log() statements will illustrate the series of events and how they are observed. I hope this may help some of you who are trying to figure out the utility of events.

  5. if the events var returns the event emitter then i dont understand how calling events.eventemitter() works..

  6. // better approach ES6 class
    class Person extends events.EventEmitter {
    constructor(name) {
    super(); = name;

    this.on('speak', (msg) => {
    console.log(`${} is speaking ${msg}`)

    const kriss = new Person('Kriss');
    kriss.emit('speak', 'hi');

  7. So…. Honestly, I didn't really understand the coolness of emitters. Can somebody explain me?
    It seems to be awesome thing, but I don't catch advantages of it

  8. here is a better way in my point of view :

    var events = require('events');

    var util = require('util');

    function person(name) {

    this.on('speak', function (msg) {

    console.log("n`"+name+"`"+" says: << "+msg+">>"+"n");

    }); function(msg) {

    this.emit("speak", msg);



    util.inherits(person, events.EventEmitter);

    var lmo7 = new person("lmo7");

    var bankour = new person("bankour");"it works baby !");"i'm in two !");

  9. I think it's a bit unclear from this video why I can't just do:
    var Person = function(name){ = name;
    this.speak = function(msg){
    console.log(`${name} said: ${msg});

    In other words, what is special about events here that can't be just done with object method? Can you perhaps give more practical example used in real world?

  10. Shaun, I think this great tutorial series needs to be updated in accordance with the newer syntax of ES6 as other commenters have pointed out.

  11. if you are using a new version of Node.js
    you dont have to require util , just use a class and extend it like the following

    const events = require('events');

    class Person extends events.EventEmitter{
    super(); = name;

    let james = new Person('james');
    let mary = new Person('mary');
    let ruy = new Person('ruy');
    let people = [james, mary, ruy];

    people.forEach(person => {
    person.on('speak', msg => {
    console.log( + ' said : ' + msg);

    james.emit('speak', 'hey dudes');

  12. I got
    'TypeError: The super constructor to "inherits" must not be null or undefined'
    This helped me (instead of events.eventEmitter):
    util.inherits(Person, events);

  13. I see there is obviously some "if this, then that" logic to it, but what is the takeaway of this? To me as a noob, this just demonstrates a complicated alternative of console.log(), to put it lightly. Shouldn't this be more like a Node JS Tutorial for Beginners #137 ?

  14. Hello net Ninja. I am a bit confused with how you are able to make james.emit as a function call when it is not on the global object.

  15. Quick question… why create an event on object if you can call straight a function of this object.
    I mean instead of writing

    james.emit('speak', 'hey dudes');

    why do not straight call a function speak:
    I mean create a function speak and write:

    james.speak('hey dudes');

    The result would be the same.
    I don't see the point to do something like that.

    Otherwise you would need to create 2 differents object (Person and Alien), add the same event
    Add Person and Alien in the same array and then call the same event in a loop for these 2 objects.
    This way I could see the point.

    In this case, why do not learn properly prototype in js and apply it.
    It will do the same thing.
    #BrainStorming lol

    Also, thanks a lot for your tutorials, they explain very well, it is very clear! 🙂

  16. Hi! I'm at 4:57 and I don't understand why the 2nd argument in emit method is directly passed as mssg. I also took a look at Node.js documentation but it's still not clear to me.

  17. Errors out saying '
    TypeError: The super constructor to "inherits" must not be null or undefined'

  18. This code did not work for me

    var events = require('events');

    var util = require('util');

    var Person = function(name){ = name;


    util.inherits(Person, events.EventEmitter);

    var sami = new Person('Sami');

    var Anes = new Person('Anes');

    var Walid = new Person('Walid');

    var people = [Sami, Anes, Walid];


    person.on('Speak', function(mssg){

    console.log( + ' Said: ' + mssg);



    sami.emit('Speak', 'Hey Dudes');

    anes.emit('Speak', 'Hey Dudes');
    This is what appeared in the Terminal

    PS C:UsersAmine BoukerdouhDesktopNode-JS-Playlist-Amine> node app
    C:UsersAmine BoukerdouhDesktopNode-JS-Playlist-Amineapp.js:94
    var people = [Sami, Anes, Walid];

    ReferenceError: Sami is not defined
    at Object.<anonymous> (C:UsersAmine BoukerdouhDesktopNode-JS-Playlist-Amineapp.js:94:15)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)

    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3
    PS C:UsersAmine BoukerdouhDesktopNode-JS-Playlist-Amine>

    please hamp me

  19. HI, best tutorials for Node.js. thanks a lot for sharing knowledge.

    I have a query Is it mandatory to give this name only : var events = require('events');

    I tried with : var diffevents= require('diffevents');
    but giving this error

    Error: Cannot find module 'diffevents'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (E:CodingNodeJsWorkspaceHandsOnsep8a.js:3:18)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)

  20. I have seen all playlist still little bit confused for routing and other ejs problem can Anyone give me another tutorial or demo link?

  21. Not sure why we need a forEach loop here. Can we not do the same thing w/o it by just having person.on function defined?

  22. seriously they're simple and short, id much rather watch a bunch of short videos than one really long one

  23. Why can't you just add a new property called speak to the Person object with the value as a function i.e.

    this.speak = function(msg){

    Or am I missing something?

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment