我想以一种很好的方式有条件地管道流。我想要实现的行为如下:
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
有什么想法吗?
答案 0 :(得分:2)
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);
从https://github.com/dashed/detour-stream/issues/2#issuecomment-231423878
发布的x