节点可读stream困境

我正在看stream这个非常漂亮的例子部分。

https://gist.github.com/joyrexus/10026630

可读性示例如下所示:

var Readable = require('stream').Readable var inherits = require('util').inherits function Source(content, options) { Readable.call(this, options) this.content = content } inherits(Source, Readable) Source.prototype._read = function (size) { if (!this.content) this.push(null) else { this.push(this.content.slice(0, size)) this.content = this.content.slice(size) } } var s = new Source("The quick brown fox jumps over the lazy dog.") console.log(s.read(10).toString()) console.log(s.read(10).toString()) console.log(s.read(10).toString()) console.log(s.read(10).toString()) console.log(s.read(10).toString()) // The quick // brown fox // jumps over // the lazy // dog. var q = new Source("How now brown cow?") q.pipe(process.stdout); 

真正让我困惑的是stream的重点不是一下子把所有东西都缓冲在内存中, 而是提供一些不同步的东西,这样一来,pipe道stream的所有内容都不会在事件循环的同一个回合中被处理。

  const writable = new stream.Writable({ write: function(chunk, encoding, cb){ console.log('data =>', String(chunk)); cb(); } }); var readable = new stream.Readable({ read: function(size){ // what do I do with this? It's required to implement } }); readable.setEncoding('utf8'); readable.on('data', (chunk) => { console.log('got %d bytes of data', chunk.length, String(chunk)); }); readable.pipe(writable); readable.push('line1'); readable.push('line2'); readable.push('line3'); readable.push('line4'); 

但我不明白的是,如何实现可读的读取方法?

看起来,我将实施阅读完全不同的例子,所以东西似乎是closures的。

如何手动读取具有可读stream的数据?

那么我知道有些东西是有点closures的,我相信这样做更接近于规范的方式:

  const writable = new stream.Writable({ write: function(chunk, encoding, cb){ console.log('data =>', String(chunk)); cb(); }, end: function(data){ console.log('end was called with data=',data); } }); var index = 0; var dataSource = ['1','2','3']; var readable = new stream.Readable({ read: function(size){ var data; if(data = dataSource[index++] ){ this.push(data); } else{ this.push(null); } } }); readable.setEncoding('utf8'); readable.on('data', (chunk) => { console.log('got %d bytes of data', chunk.length, String(chunk)); }); readable.pipe(writable); 

我不相信开发者应该明确地打电话给read ; read是由开发人员实施,但不是所谓的。 希望这是正确的。 我唯一的问题就是为什么没有在可写入stream中调用end 。 我也很好奇为什么阅读不会callback。