我想以一种很好的方式有条件地管道流。我想要实现的行为如下:
if (someBoolean) {
stream = fs
.createReadStream(filepath)
.pipe(decodeStream(someOptions))
.pipe(writeStream);
} else {
stream = fs
.createReadStream(filepath)
.pipe(writeStream);
}
所以我准备了我所有的流,如果someBoolean
是真的,我想向管道添加一个额外的流。
然后我想我找到了绕道流的解决方案,但不幸的是没有设法设置它。我使用了类似于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
有什么想法吗?
>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