Celaro
Celaro

Reputation: 226

NodeJS cannot read property 'on' of undefined

I am encountering a wear error message on NodeJS and I have been looking around with no success. I have looked at similar questions, but nothing help to fix the error. I am trying to create a Duplex Stream but whenever I run it, I am receiving the error message from Node as it 'cannot read property 'on' of undefined. However every thing seems right in the code below. Any help would be greatly appreciated. Thank you!

//duplex stream used for read and writing

var stream = require('stream');
var util = require('util');

util.inherits(ReadWrite, stream.Duplex);

function ReadWrite(opt){

stream.Duplex.call(this, opt);
this.array = [];
};

//register two functions read and write 
ReadWrite.prototype._read = function(size){

//stores the first item 
var data = this.array.shift(); 

if(data == 'stop'){

    this.push(null);
}
else{

    if(data){

        this.push(data);
    }
    else{

        setTimeout(_read.bind(this), 500, size);
    }
}
};


 ReadWrite.prototype._write = function(data, encode, callback){

  this.array.push(data);
  callback;
 };

//testing

var buf = ReadWrite();

 buf.on('data', function(data){

  console.log('Read: ' + data.toString());
 });

 buf.on('end', function(){

    console.log('Message complete!');
 });

 buf.write('Bonjour');
 buf.write("C'est Moi");
 buf.write('On dit quoi?');

Upvotes: 0

Views: 3600

Answers (2)

jfriend00
jfriend00

Reputation: 708056

You do this:

var buf = ReadWrite();
buf.on(...)

But, ReadWrite() does not return anything as it is just this code:

function ReadWrite(opt){
    stream.Duplex.call(this, opt);
    this.array = [];
};

Perhaps you mean to do this instead so it will create a new ReadWrite object and return it as this is the usual way to create new objects with new:

var buf = new ReadWrite();

Upvotes: 0

CharlieBrown
CharlieBrown

Reputation: 4163

Isn't there a typo here?

ReadWrite.prototype_write = function(data, encode, callback){

You wrote prototype_write instead of prototype._write.

The following works:

function ReadWrite(opt){
  // this is needed if you don't use new ReadWrite()
  if(!this instanceof ReadWrite){
    return new ReadWrite(opt)
  }
  Duplex.call(this, opt);
}

util.inherits(ReadWrite, Duplex);

var test = new ReadWrite()

You forgot to use new ReadWrite() when creating an instance.

Upvotes: 1

Related Questions