Node.js Cannot read property 'on' of undefined

25,212

Solution 1

You forgot to return the event emitter from your v function:

var v = function() {
    var e = new events();
    e.emit('start');
    return e;
};

Also notice that the start event will not be called because you have emitted the event before you subscribed to it. So you could kind of rework your code a little:

var events = require('events').EventEmitter;
var v = function() {
    var e = new events();
    return e;
};

var r = v();
r.on('start', function(){
    console.log('event start just fired!!!!!!!!!!');
});

// emit the event after you have subscribed to the start callback
r.emit('start');

Solution 2

r is undefined, since v isn't returning anything. That's why you're getting the error. And even if you return the event, your code won't give you the desired output, since you need to use on("start") before you use emit("start")

var events = require('events').EventEmitter;

var e = new events();

e.emit('start'); //This won't trigger the console.log

//Need to be binded before you emit the event.
e.on('start', function(){
    console.log('event start just fired!!!!!!!!!!');
});

e.emit('start'); //This will trigger the console.log
Share:
25,212
Milad
Author by

Milad

Updated on July 09, 2022

Comments

  • Milad
    Milad almost 2 years

    What is wrong?

    p.s. : I am new to node.js and I'm from .Net world!

    My server.js code :

        var events = require('events').EventEmitter;
        var v = function() {
            var e = new events();
            e.emit('start');
        };
    
        var r = v();
        r.on('start', function(){
            console.log('event start just fired!!!!!!!!!!');
        });
    

    and this console output :

    TypeError: Cannot read property 'on' of undefined
        at Object.<anonymous> (E:\Project\node\BasicSocial\server.js:12:2)
        at Module._compile (module.js:410:26)
        at Object.Module._extensions..js (module.js:417:10)
        at Module.load (module.js:344:32)
        at Function.Module._load (module.js:301:12)
        at Function.Module.runMain (module.js:442:10)
        at startup (node.js:136:18)
        at node.js:966:3