Concatenate two (or n) streams

前端 未结 10 1266
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-24 02:34
  • 2 streams:

    Given readable streams stream1 and stream2, what\'s an idiomatic (concise) way to get a stream containing

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 03:02

    This can now be easily done using async iterators

    async function* concatStreams(readables) {
      for (const readable of readables) {
        for await (const chunk of readable) { yield chunk }
      }
    } 
    

    And you can use it like this

    const fs = require('fs')
    const stream = require('stream')
    
    const files = ['file1.txt', 'file2.txt', 'file3.txt'] 
    const iterable = await concatStreams(files.map(f => fs.createReadStream(f)))
    
    // convert the async iterable to a readable stream
    const mergedStream = stream.Readable.from(iterable)
    

    More info regarding async iterators: https://2ality.com/2019/11/nodejs-streams-async-iteration.html

提交回复
热议问题