NodeJS无法读取' on'未定义的

时间:2017-02-05 08:16:52

标签: node.js

我在NodeJS上遇到一条磨损错误信息,我一直在环顾四周但没有成功。我看过类似的问题,但没有任何帮助来解决错误。我正在尝试创建一个双工流,但每当我运行它时,我收到来自Node的错误消息,因为它无法读取属性' on'未定义的。但是,下面的代码中的每件事情都是正确的。任何帮助将不胜感激。谢谢!

//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?');

2 个答案:

答案 0 :(得分:1)

这里有拼错吗?

Highcharts.stockChart('chartcontainer', { rangeSelector: { selected: 1 }, title: { text: 'AAPL Stock Price' }, plotOptions: { candlestick: { color: '#00c800', upColor: '#c80000' } }, series: [{ type: 'candlestick', name: 'AAPL Stock Price', data: data, dataGrouping: { units: [ [ 'week', // unit name [1] // allowed multiples ], [ 'month', [1, 2, 3, 4, 6] ] ] } }] });

你写了 prototype_write 而不是ReadWrite.prototype_write = function(data, encode, callback){

以下作品:

prototype._write

您在创建实例时忘记使用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()

答案 1 :(得分:0)

你这样做:

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

但是,ReadWrite()不会返回任何内容,因为它只是这段代码:

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

也许你的意思是这样做,所以它会创建一个新的ReadWrite对象并返回它,因为这是用new创建新对象的常用方法:

var buf = new ReadWrite();