【问题标题】:Conditionally pipe streams in Node.jsNode.js 中的有条件管道流
【发布时间】:2016-02-24 15:13:13
【问题描述】:

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

if (someBoolean) {

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

} else {

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

}

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

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

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

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

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

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

有什么想法吗?

【问题讨论】:

    标签: node.js stream


    【解决方案1】:

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

    因此,从您的示例来看,这应该有效:

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

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

    【讨论】:

    • 这是显而易见的。 :-) 我没想到,谢谢!
    • 现在似乎不起作用,每当使用 detour 时,我的流都会过早结束,当我硬编码时工作正常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2017-04-21
    • 2014-09-13
    • 2013-07-02
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多