Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally pipe streams in Node.js

Tags:

stream

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?

like image 562
Julian Avatar asked Sep 26 '22 06:09

Julian


People also ask

What is stream pipe in node JS?

pipe() is file streams. In Node. js, fs. createReadStream() and fs. createWriteStream() are used to create a stream to an open file descriptor.

Are Nodejs streams async?

The Node. js Stream API has been around for a long time and is used as a uniform API for reading and writing asynchronous data.

What is pipe in stream?

A stream pipe is a UNIX interprocess communication (IPC) facility that allows processes on the same computer to communicate with each other.


1 Answers

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

like image 66
Alberto Leal Avatar answered Sep 28 '22 07:09

Alberto Leal