为什么这个streamfunction会导致错误?
我已经编写了一个函数,将input的参数logging到控制台。
function sconsole() { var stream = new Stream.Transform({objectMode: true}), foo = [].slice.call(arguments); stream._transform = function (data, encoding, callback) { console.log.apply(null, foo); callback(null, data); }; return stream; }
使用示例:
stream .pipe(sconsole('foo')) .pipe(...);
但是,当用于一系列pipe道调用的最终位置时,会导致以下错误:
TypeError: Invalid non-string/buffer chunk
为什么?
您不能像混合/pipe道objectMode
和非objectMode
stream,因为它们使用不同的数据types。
但是,如果您有节点v0.12 +或io.js,则可以使用诸如readableObjectMode: true
设置,它将变换stream的可读面设置为读取对象,但是正常写入字节。 你可以通过其他的方法来做类似的事情writableObjectMode: true
使用writableObjectMode: true
( objectMode: true
相当于将这两个属性设置为true
)。 这样你可以在一个streamtypes之间转换。