【发布时间】:2017-05-29 15:29:38
【问题描述】:
我刚刚创建了一个简单的可读可写流对,它可以与 pipe() 连接。我对创建背压和控制 Readable 中发生读取的速率感兴趣。但是,我对如何实际实现这一点或者是否可以使用 Node.js 流有点困惑。 举个例子:
const {Writable, Readable} = require('stream');
function getWritable() {
return new Writable({
write: function (chunk, encoding, cb) {
console.log(' => chunk => ', String(chunk));
setTimeout(cb, 1500);
}
});
}
function getReadable(data) {
return new Readable({
encoding: 'utf8',
objectMode: false,
read: function (n) {
// n => Number(16384)
console.log('read is called');
const d = data.shift();
this.push(d ? String(d) : null);
}
});
}
const readableStrm = getReadable([1, 2, 3, 4, 5]);
const piped = readableStrm.pipe(getWritable());
piped.on('finish', function () {
console.log('finish');
});
如果你运行上面的代码,我们会看到'read is called'会被记录 5 次,远在 Writable 中的 write 方法看到数据之前。
我想做的是仅在 Writable 中的 write 方法触发其回调时才在 Readable 中调用 read();当然 read() 方法必须先触发一次,但随后会等待可写对象准备好。
有没有办法控制read() 方法何时以某种方式在可读文件中触发?
最后,我真的不明白read()方法的目的是什么。
作为一个简单的例子,无论我从 read() 返回什么,我都无法让它停止阅读。 read 方法的意义何在,我们为什么要实现它?
const Readable = require('stream').Readable;
const r = new Readable({
objectMode: true,
read: function (n) {
console.log('is read');
return false/null/true; // nothing I return here makes a difference
}
});
r.on('data', function (d) {
console.log(d);
});
setInterval(function(){
r.push('valid');
},1000);
【问题讨论】:
标签: javascript node.js