请注意,有许多转换流可以做到这一点:
JSON -> JS
但我希望创建一个可以执行以下操作的 Node.js 转换流:
JS -> JSON
我有一个可读的流:
const readable = getReadableStream({objectMode:true});
可读流输出对象,而不是字符串。
我需要创建一个转换流,它可以过滤其中一些对象并将对象转换为 JSON,如下所示:
const t = new Transform({
objectMode: true,
transform(chunk, encoding, cb) {
if(chunk && chunk.marker === true){
this.push(JSON.stringify(chunk));
}
cb();
},
flush(cb) {
cb();
}
});
但是,由于某种原因,我的转换流不能接受转换方法的对象,只有字符串和缓冲区,我该怎么办?
我尝试添加这两个选项:
const t = new Transform({
objectMode: true,
readableObjectMode: true, // added this
writableObjectMode: true, // added this too
transform(chunk, encoding, cb) {
this.push(chunk);
cb();
},
flush(cb) {
cb();
}
});
不幸的是,我的转换流仍然不能接受对象,只能接受字符串/缓冲区。