简体   繁体   中英

How to return w filtred Readable stream from another readablestream

I'm triying to filter the data in the inputStream then return it into the outputStream,this is the example i'm working on:

const filterStream = async (inputStream, regexp) => {
      let outputStream = inputStream;
      outputStream.on("data", (data) => {
        if (data.match(regexp)) return data;
      });    
      return outputStream;
    };

    const inputStream = stream.Readable.from(["aaa", "aAa", "aab"]).setEncoding(
      "utf8"
    );
    
    const outputStream = filterStream(inputStream, /aaa/i);
    console.log('data of outputstream')

I found a solution on the web that uses stream.Tranform, is there any other methode

Thanks for your help

I used Transform to update the data in my initial Readable Stream inputstream , this is what i did:

const filterStream = async (inputStream, regexp) => {
  let outputStream = inputStream;
  outputStream = inputStream.pipe(
    new stream.Transform({
      objectMode: true,
      transform(chunk, encoding, callback) {
        let data = chunk.toString();
        if (data.match(regexp)) {
          //we can push data and call the callback 
          this.push(data);
          callback();
          // or just call the callback with data as params 
          // callback(null, data);
        }
      },
    })
  );

  outputStream.on("data", (data) => {
    console.log(data);
  });
  return outputStream;
  }

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