我正在为 gulp 编写一个插件,它使用网络服务,并根据响应执行一项或多项操作。算法是这样的:
stream1 = through.obj(function(src, enc, cb) {
if src.is_a_buffer()
http_request(options)
http_request.on('response', function () {
if (statusCode = 200) {
/* Normal course, everything works fine here */
do_something()
return cb()
} else {
/* Exception course, although the stream2 is created, is never executed */
stream1.pipe(stream2())
}
}, function (cb) {
cb()
});
stream2 = through.obj(function(src,enc,cb) {
do_other_stuff()
stream2.push(src)
return cb()
}, function (cb) {
cb()
});
当我运行代码时,stream2 永远不会执行。 由于我是 Node 流的新手,我想我误解了一些东西。你们中的任何人都可以帮我理解我在这里做错了什么吗?
最佳答案
当您调用stream1.pipe(stream2())
时,stream1
已经发出数据(可能是全部);进行该调用不会将执行传递给 stream2
。根据您的需要,可以通过多种方法来处理:
注意:我只是在这里修改原始伪代码
选项 1:
不必费心使用stream2
,只需直接调用do_other_stuff()
即可:
stream1 = through.obj(function(src, enc, cb) {
if src.is_a_buffer()
http_request(options)
http_request.on('response', function () {
if (statusCode = 200) {
/* Normal course, everything works fine here */
do_something()
cb()
} else {
do_other_stuff()
cb()
}
}, function (cb) {
cb()
});
选项 2:
如果您需要 stream2
用于其他目的,请将 through.obj()
回调拉出到其自己的可调用函数中,并直接从 else 子句中调用它。
stream1 = through.obj(function(src, enc, cb) {
if src.is_a_buffer()
http_request(options)
http_request.on('response', function () {
if (statusCode = 200) {
/* Normal course, everything works fine here */
do_something()
return cb()
} else {
processStream2(src, enc, cb)
}
}, function (cb) {
cb()
});
function processStream2(src, enc, cb) {
do_other_stuff()
return cb()
}
stream2 = through.obj(processStream2, function (cb) {
cb()
});
希望有帮助:)
关于javascript - 如何重定向基于 "internal state"的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24985826/