gpt4 book ai didi

node.js - _read()的 Node 可读流什么时候调用

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:41 26 4
gpt4 key购买 nike

我创建自己的阅读流。但我想知道_read()什么时候被调用?如果我不添加on('data')监听器,_read()就不会被调用,为什么?

var data = [{"id":0,"name":"object 0","value":3}],
Readable = require('stream').Readable,
util = require('util');

var ReadStream = function() {
Readable.call(this, {objectMode: true});
this.data = data;
this.curIndex = 0;
};
util.inherits(ReadStream, Readable);

ReadStream.prototype._read = function() {
if (this.curIndex === this.data.length)
return this.push(null);

var data = this.data[this.curIndex++];
//console.log('read: ' + JSON.stringify(data));
this.push(data);
};


var stream = new ReadStream();
stream.on('data', function(record) {
console.log('received: ' + JSON.stringify(record));
});

stream.on('end', function() {
console.log('done111');
});

最佳答案

If I don't add on('data') listerner, the _read() will not be called. Why?

流已暂停。假设您使用的是最新版本的 Node 。

https://nodejs.org/api/stream.html#stream_two_modes

All Readable streams begin in paused mode but can be switched to flowing mode in one of the following ways:

Adding a 'data' event handler.

Calling the stream.resume() method.

Calling the stream.pipe() method to send the data to a Writable.

顺便说一句,要创建可读的,请检查 nomsmississippi.from

关于node.js - _read()的 Node 可读流什么时候调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38204337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com