如何实现基本节点Stream.Readable示例?

我正在尝试学习stream,并有一点问题让它正常工作。

对于这个例子,我只是想推动一个静态对象的stream和pipe道到我的服务器响应。

这是我迄今为止,但很多不起作用。 如果我甚至可以让stream输出到控制台,我可以弄清楚如何将其输出到我的响应。

var Readable = require('stream').Readable; var MyStream = function(options) { Readable.call(this); }; MyStream.prototype._read = function(n) { this.push(chunk); }; var stream = new MyStream({objectMode: true}); s.push({test: true}); request.reply(s); 

当前的代码有几个问题。

  1. 请求stream最有可能是一个缓冲模式stream:这意味着你不能写入对象。 幸运的是,您不会将选项传递给Readable构造函数,因此您的错误不会造成任何麻烦,但在语义上这是错误的,不会产生预期的结果。
  2. 您可以调用Readable的构造函数,但不要inheritance原型属性。 你应该使用util.inherits()util.inherits() Readable
  3. chunkvariables没有在您的代码示例中的任何位置定义。

这是一个工作的例子:

 var util = require('util'); var Readable = require('stream').Readable; var MyStream = function(options) { Readable.call(this, options); // pass through the options to the Readable constructor this.counter = 1000; }; util.inherits(MyStream, Readable); // inherit the prototype methods MyStream.prototype._read = function(n) { this.push('foobar'); if (this.counter-- === 0) { // stop the stream this.push(null); } }; var mystream = new MyStream(); mystream.pipe(process.stdout);