为什么nodejs可读流跳过第一个字母?

时间:2016-10-29 04:40:13

标签: node.js stream

var util = require('util');
var ReadableStream = require('stream').Readable;

function MyReadStream() {
    ReadableStream.call(this);
    this._index = 0;
    this._string = 'Hello World!';
}

util.inherits(MyReadStream, ReadableStream);

MyReadStream.prototype._read = function() {
    var i = this._index++;
    if (i == this._string.length) {
      this.push(null);
      this.pipe(process.stdout);
    }
    else {
      var buf = new Buffer(this._string[i], 'utf8');
      this.push(buf);
    }
 };

 var readerInst = new MyReadStream();
 readerInst.read();

============================================== < / p>

为什么我得到了stdout&#39; ello World!&#39;而不是&#39; Hello World!&#39;?

1 个答案:

答案 0 :(得分:0)

正在发生的事情是readerInst.read()(要求任意数量的字节)导致_read()被执行,因为还没有要读取的数据,所以_read()推送第一个字符到流,然后由readerInst.read()返回。在该调用完成之后,字符串的其余部分被推送到流中,当到达字符串的末尾时,内容被管道/写入stdout,这将仅显示从第二个字母开始的字符串。 / p>

您可以通过记录readerInst.read()的返回值来验证这种情况。

相关问题