Node.js 中的有条件管道流

Jul*_*ian 5 stream node.js

我想以一种很好的方式有条件地管道流。我想要实现的行为如下:

if (someBoolean) {

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

} else {

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

}
Run Code Online (Sandbox Code Playgroud)

所以我准备了我所有的流,如果someBoolean是真的,我想向管道添加一个额外的流。

然后我以为我找到了detour-stream的解决方案,但不幸的是没有设法设置它。我使用了类似于gulp-if 的符号,因为这被提到作为灵感:

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

stream = fs
  .createReadStream(filepath)
  .detour(someBoolean, decodeStream(someOptions))
  .pipe(writeStream);
Run Code Online (Sandbox Code Playgroud)

但不幸的是,这只会导致错误:

  .detour(someBoolean, decodeStream(someOptions))
 ^
TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Alb*_*eal 5

detour是一个创建可写流的函数:https ://nodejs.org/api/stream.html#stream_read_pipe_destination_options

因此,从你的例子来看,这应该有效:

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

stream = fs
  .createReadStream(filepath)
  .pipe(detour(someBoolean, decodeStream(someOptions))) // just pipe it
  .pipe(writeStream);
Run Code Online (Sandbox Code Playgroud)

x-发布自https://github.com/dashed/detour-stream/issues/2#issuecomment-231423878