Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two (or n) streams

  • 2 streams:

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

    I cannot do stream1.pipe(outStream); stream2.pipe(outStream), because then the stream contents are jumbled together.

  • n streams:

    Given an EventEmitter that emits an indeterminate number of streams, e.g.

    eventEmitter.emit('stream', stream1) eventEmitter.emit('stream', stream2) eventEmitter.emit('stream', stream3) ... eventEmitter.emit('end') 

    what's an idiomatic (concise) way to get a stream with all streams concatenated together?

like image 699
Jo Liss Avatar asked May 08 '13 01:05

Jo Liss


People also ask

Can we use same stream twice?

From the documentation: A stream should be operated on (invoking an intermediate or terminal stream operation) only once. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. So the answer is no, streams are not meant to be reused.

What is stream () in Java?

A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.


2 Answers

The combined-stream package concatenates streams. Example from the README:

var CombinedStream = require('combined-stream'); var fs = require('fs');  var combinedStream = CombinedStream.create(); combinedStream.append(fs.createReadStream('file1.txt')); combinedStream.append(fs.createReadStream('file2.txt'));  combinedStream.pipe(fs.createWriteStream('combined.txt')); 

I believe you have to append all streams at once. If the queue runs empty, the combinedStream automatically ends. See issue #5.

The stream-stream library is an alternative that has an explicit .end, but it's much less popular and presumably not as well-tested. It uses the streams2 API of Node 0.10 (see this discussion).

like image 34
Jo Liss Avatar answered Sep 17 '22 02:09

Jo Liss


this can be done with vanilla nodejs

import { PassThrough } from 'stream' const merge = (...streams) => {     let pass = new PassThrough()     let waiting = streams.length     for (let stream of streams) {         pass = stream.pipe(pass, {end: false})         stream.once('end', () => --waiting === 0 && pass.emit('end'))     }     return pass } 
like image 87
Feng Avatar answered Sep 17 '22 02:09

Feng