简体   繁体   中英

add in the middle of a pipe stream node js

I'm currently building a scheduling application in 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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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