Julian
Julian

Reputation: 418

Conditionally pipe streams in Node.js

I want to conditionally pipe streams in a nice way. The behaviour I want to achieve is the following:

if (someBoolean) {

  stream = fs
    .createReadStream(filepath)
    .pipe(decodeStream(someOptions))
    .pipe(writeStream);

} else {

  stream = fs
    .createReadStream(filepath)
    .pipe(writeStream);

}

So I prepared all my streams, and if someBoolean is true, I want to add an additional stream to the pipe.

Then I thought I found a solution with detour-stream, but unfortunately didn't manage to set this up. I used notation similar to gulp-if, because this was mentioned as inspiration:

var detour = require('detour-stream');

stream = fs
  .createReadStream(filepath)
  .detour(someBoolean, decodeStream(someOptions))
  .pipe(writeStream);

But this unfortunately only results in an error:

  .detour(someBoolean, decodeStream(someOptions))
 ^
TypeError: undefined is not a function

Any ideas?

Upvotes: 5

Views: 3122

Answers (1)

Alberto Leal
Alberto Leal

Reputation: 520

detour is a function that creates a writable stream: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options

Thus, from your example, this should work:

var detour = require('detour-stream');

stream = fs
  .createReadStream(filepath)
  .pipe(detour(someBoolean, decodeStream(someOptions))) // just pipe it
  .pipe(writeStream);

x-posted from https://github.com/dashed/detour-stream/issues/2#issuecomment-231423878

Upvotes: 5

Related Questions