簡體   English   中英

在管道流節點js中添加

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM