Node.js 流对象模式

标签 node.js asynchronous stream pipe monads

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

// 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 并不安全。”

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

最佳答案

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

Streams that are in object mode can emit generic JavaScript values other than Buffers and Strings.

你的例子是安全的,它只是进行转换 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);

关于Node.js 流对象模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20440285/

相关文章:

node.js - 调用 activator.init 后,Sequelize 急切加载会引发错误

visual-studio-2010 - 在 Windows x64 上安装 node-canvas 平台 x64 无效?

c# - 串行端口异步读取(非阻塞)+ 线程

macos - osx 上的 aio : Is it implemented in the kernel or with user threads? 其他选项?

c# - 在等待 List<Task> 中的所有任务完成时显示进度

javascript - oncanplay 与 oncanplaythrough

c# - 从 Compact Framework 客户端进行 REST 调用时如何避免 "Bad Request - Invalid Hostname"错误?

javascript - 在嵌套的 then 和 promises ExpressJS/NodeJs 中返回错误

javascript - 将模板引擎加载到node.js/express中

c++ - noskipws对cin的影响>>