【问题标题】:Node.js Stream objectModeNode.js 流对象模式
【发布时间】:2013-12-07 10:33:04
【问题描述】:

我试图理解对象流的概念,尤其是两者的结合。我正在寻找的用法是将字节流与对象流一起管道,例如:

// StringifyStream reads Buffers and emits String Objects
// Mapper is really just a classical map
// BytifyStream reads String Objects and emits buffers.

process.stdin.pipe(
   StringifyStream()
).pipe( 
   Mapper(function(s) {
      return s.toUpperCase();
}).pipe(
    BytifyStream()
).pipe(process.stdout);

// This code should read from stdin, convert all incoming buffers to strings,
// map those strings to upper case and finally convert them back to buffers
// and write them to stdout.

现在,文档说:

“在中途设置 objectMode 是不安全的。”

我真的不明白这是什么意思。混合字节/对象流不安全吗?我真的很想使用这种模式,但如果它不安全,那可能是个坏主意。

【问题讨论】:

    标签: node.js asynchronous stream pipe monads


    【解决方案1】:

    对象流是那些发出 Buffer 或 String 以外的数据类型的流。

    处于对象模式的流可以发出除缓冲区和字符串之外的通用 JavaScript 值。

    你的例子是安全的,它只是转换 Buffer -> string -> upper string -> Buffer。

    这只是我的意见,但您可以简化链并仅使用一个 Transform 流。

    var util = require ("util");
    var stream = require ("stream");
    
    var UpperStream = function (){
        stream.Transform.call (this);
    };
    
    util.inherits (UpperStream, stream.Transform);
    
    UpperStream.prototype._transform = function (chunk, encoding, cb){
        this.push ((chunk + "").toUpperCase ());
        cb ();
    };
    
    process.stdin.pipe (new UpperStream ()).pipe (process.stdout);
    

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 2014-07-24
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      相关资源
      最近更新 更多