简体   繁体   English

在管道流节点js中添加

[英]add in the middle of a pipe stream node js

I'm currently building a scheduling application in nodeJS. 我目前正在nodeJS中构建调度应用程序。

I have a template of a schedule that i'd like to generate dynamically. 我有一个时间表的模板,我想动态生成。 I know this is possible with stream, more specifically with pipes although I'm unable to get it to inject code in the middle of the stream. 我知道这在流中是可能的,更具体地说是在管道中,尽管我无法使其在流中注入代码。

What I've tried: 我尝试过的

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();
        }))

this simply doesn't change anything. 这根本不会改变任何东西。

I've also tried to make my own custom transform class 我也尝试制作自己的自定义转换类

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}');

but this only adds to the end of the steam. 但这只会增加蒸汽的消耗。

String replace works only for one line. 字符串替换仅适用于一行。
My issue is that I need to replace that one line with multiple new lines. 我的问题是我需要用多行新行替换这一行。

Is it possible to use async generator ( async *function ) and async iterator ( for await ) for this? 是否可以为此使用异步生成器( async *function )和异步迭代器( for await )? It would be roughly like this: 大概是这样的:

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()) {
    .....
}

Async iterators are available on ES2018/Node 10 异步迭代器在ES2018 / Node 10上可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM