[英]add in the middle of a pipe stream node js
我目前正在nodeJS中构建调度应用程序。
我有一个时间表的模板,我想动态生成。 我知道这在流中是可能的,更具体地说是在管道中,尽管我无法使其在流中注入代码。
我尝试过的
var through2 = require( "through2" );
input.pipe(through2(function (chunk, encoding, done){
var transformChunk = chunk.toString()
console.log(transformChunk);
if (transformChunk.includes("\\newDay{}{}")){
transformChunk += "newDay{12}{12}";
this.push(transformChunk);
}
done();
}))
这根本不会改变任何东西。
我也尝试制作自己的自定义转换类
const { Transform } = require('stream');
class injectText extends Transform {
constructor(string){
super();
this.replaceString = string;
}
_transform(chunk, encoding, callback) {
// var transformChunk = chunk.toString().replace("newDay{}{}", this.replaceString);
var transformChunk = chunk.toString()
if (transformChunk.includes("newDay{}{}")){
transformChunk += "newDay{12}{12}";
}
this.push(transformChunk)
console.log(transformChunk);
callback();
}
};
var changedStream = new injectText('newDay{11}{11}');
但这只会增加蒸汽的消耗。
字符串替换仅适用于一行。
我的问题是我需要用多行新行替换这一行。
是否可以为此使用异步生成器( async *function
)和异步迭代器( for await
)? 大概是这样的:
async *inputGenerator() {
for await (const chunk of input) {
var transformedChunk = chunk.toString();
if (transformedChunk.includes("\\newDay{}{}")){
transformedChunk += "newDay{12}{12}";
}
yield transformedChunk;
}
}
// do something with the transformed input
for await (const chunk of inputGenerator()) {
.....
}
异步迭代器在ES2018 / Node 10上可用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.