Ale*_*lls 6 node.js node-streams nodejs-stream
这个问题是如何真正实现可读流的read方法。
我有一个Readable流的实现:
import {Readable} from "stream";
this.readableStream = new Readable();
Run Code Online (Sandbox Code Playgroud)
我收到此错误
events.js:136 throw er; //未处理的“错误”事件^
错误[ERR_STREAM_READ_NOT_IMPLEMENTED]:未在Readable._read(_stream_visible.js:445:10)处在readable.read(_stream_read.js:445:10)在_combinedTickCallback处的履历(_stream_read.js:445:10)上未实现_read() (内部/流程/next_tick.js:138:11)在启动时(bootstrap_node)在Function.Module.runMain(模块.js:684:11)的process._tickCallback(内部/流程/next_tick.js:180:9) js:191:16)在bootstrap_node.js:613:3
错误发生的原因很明显,我们需要这样做:
this.readableStream = new Readable({
read(size) {
return true;
}
});
Run Code Online (Sandbox Code Playgroud)
我不太了解如何实现read方法。
唯一可行的就是打电话
this.readableStream.push('some string or buffer');
Run Code Online (Sandbox Code Playgroud)
如果我尝试做这样的事情:
this.readableStream = new Readable({
read(size) {
this.push('foo'); // call push here!
return true;
}
});
Run Code Online (Sandbox Code Playgroud)
然后什么也没发生-可读性就没有了!
此外,这些文章说您不需要实现read方法:
https://github.com/substack/stream-handbook#creating-a-visible-stream
https://medium.freecodecamp.org/node-js-streams-everything-you-need-to-know-c9141306be93
我的问题是 -为什么在read方法中调用push不起作用?对我唯一有用的就是在其他地方调用read.push()。
为什么在read方法中调用push不起作用?对我唯一有用的就是在其他地方调用read.push()。
我认为这是因为您没有使用它,而是需要将其通过管道传输到可写流(例如stdout),或者仅通过data事件使用它:
const { Readable } = require("stream");
let count = 0;
const readableStream = new Readable({
read(size) {
this.push('foo');
if (count === 5) this.push(null);
count++;
}
});
// piping
readableStream.pipe(process.stdout)
// through the data event
readableStream.on('data', (chunk) => {
console.log(chunk.toString());
});
Run Code Online (Sandbox Code Playgroud)
两者都应打印5次foo(尽管有些不同)。您应该使用哪一个取决于您要完成的工作。
此外,这些文章说您不需要实现read方法:
您可能不需要它,这应该可以工作:
const { Readable } = require("stream");
const readableStream = new Readable();
for (let i = 0; i <= 5; i++) {
readableStream.push('foo');
}
readableStream.push(null);
readableStream.pipe(process.stdout)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您无法通过data事件捕获它。而且,这种方式不是很有用,效率也不高,我们只是立即推送流中的所有数据(如果很大,所有内容都将存储在内存中),然后使用它。
| 归档时间: |
|
| 查看次数: |
5586 次 |
| 最近记录: |