Technologies Web

Use the same stream multiple times

Hi everibody.

Today I want to share with you something that I discovered after several hours of searching and trying. I’m talking about use the same stream multiple times. Know that you can solve this problem only with the basic tools provided in NodeJS.

Normally, when you eat a flow, we can not do anything if the done method was called. To bypass this limitation, I’ll tell you about the PassThrough streams. Here’s what NodeJS documentation says about them :

This is a trivial implementation of a Transform stream that simply passes the input bytes across to the output. Its purpose is mainly for examples and testing, but there are occasionally use cases where it can come in handy as a building block for novel sorts of streams.

We will use it here to copy our stream several times and use it as many times we create PassThrough. To create a PassThrough stream from another stream, it’s very simple :

// we include nodeJS stream API
var Stream = require('stream');
// our source stream.
var stream; 
// we create empty PassThrough stream
var copyStream1 = new Stream.PassThrough(),
    copyStream2 = new Stream.PassThrough();
// copy source stream into PassThrough stream

Now, we only can use copyStream1 and copyStream2 but, in fact, it’s like using our stream twice. I hope this tip will be useful