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