【问题标题】:How do I implement a basic node Stream.Readable example?如何实现基本节点 Stream.Readable 示例?
【发布时间】:2014-01-09 15:17:09
【问题描述】:

我正在尝试学习流,但在使其正常工作时遇到了一点问题。

对于这个例子,我只是想将一个静态对象推送到流中,然后通过管道将它传递给我的服务器响应。

这是我目前所拥有的,但很多都不起作用。如果我什至可以将流输出到控制台,我就能弄清楚如何将它通过管道传输到我的响应中。

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);

【问题讨论】:

    标签: javascript node.js stream


    【解决方案1】:

    您当前的代码存在几个问题。

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

    这是一个工作示例:

    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);
    

    【讨论】:

    • 我对如何将内容推送到流中感到困惑。我看到您正在推送 foobar,但我需要将内容推送到 mystream 实例。我该怎么做?
    • 你运行代码了吗? this.push() 函数调用意味着将数据推送到读取队列。这意味着您推送的所有内容都可供流的消费者使用(这里是process.stdout 流)。
    • 您还应该阅读Stream Handbook,尤其是创建可读流部分。
    • 因为对象的原型是stream.Readable,是的
    • 可读流是 node.js 世界中最不直观的东西。
    猜你喜欢
    • 2014-08-21
    • 2018-03-29
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    相关资源
    最近更新 更多