我试图了解流如何在nodejs中工作。为此,我编写了这段代码
'use strict'
var fs = require('fs')
var split = require('split')
var stream = require('stream')
const myTransform = new stream.Transform({
writableObjectMode: true,
readableObjectMode: true,
transform (chunk, encoding, callback) {
console.log('transform', chunk) // chunk is a string
this.push({chunk: chunk})
callback()
}
})
const myWritable = new stream.Writable({
objectMode: true,
write (chunk, encoding, callback) {
console.log('writable', chunk)
callback()
}
})
myWritable.on('finish', () => console.log('FINISHED'))
fs.createReadStream(__dirname + '/prova.txt')
.pipe(split())
.pipe(myTransform)
.pipe(myWritable)
此示例运行良好,但我不明白为什么如果转换流将
readableObjectMode
设置为false
,脚本将失败transform line1
stream.js:74
throw er; // Unhandled stream error in pipe.
^
TypeError: Invalid non-string/buffer chunk
at chunkInvalid (_stream_readable.js:380:10)
at readableAddChunk (_stream_readable.js:125:12)
at Transform.Readable.push (_stream_readable.js:111:10)
at Transform.push (_stream_transform.js:128:32)
at Transform.transform [as _transform] (/path/to/mystream.js:12:10)
at Transform._read (_stream_transform.js:167:10)
at Transform._write (_stream_transform.js:155:12)
at doWrite (_stream_writable.js:301:12)
at writeOrBuffer (_stream_writable.js:287:5)
at Transform.Writable.write (_stream_writable.js:215:11)
最佳答案
该文档不是很清楚,但是readableObjectMode
相对于“读取侧”。因此,如果为true,则可以推动对象。否则,必须使用字符串或缓冲区writableObjectMode
相对于“写面”。因此,方法transform
具有一个对象作为第一个参数。
因此,在上面的示例中,writableObjectMode
参数可以设置为false
。
注意:如果writableObjectMode
设置为false
,则transform方法将Buffer
的实例接收为chunk