【问题标题】:How can I redirect a stream based in an "internal state"如何重定向基于“内部状态”的流
【发布时间】:2014-09-19 02:02:00
【问题描述】:

我正在为 gulp 编写一个使用 Web 服务的插件,并根据响应做一件事或另一件事。算法是这样的:

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 时,它永远不会执行。 由于我是节点流的新手,我想我误解了一些东西。你们中的任何人都可以帮助我理解我在这里做错了什么吗?

【问题讨论】:

  • 这应该是纯 javascript 还是转换为 javascript 的语言?如果是前者,那么右侧值为 return <value> 的赋值是无效的 javascript ...
  • @mscdex 我的错。已编辑

标签: javascript node.js stream gulp


【解决方案1】:

当您调用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()
});

希望对你有帮助:)

【讨论】:

  • 第二个选项完全适合我的场景,现在看起来很简单:D。我只需要一个可以在流之间共享的转换函数。谢谢!
  • 太棒了!我很高兴能帮上忙:)
猜你喜欢
  • 1970-01-01
  • 2012-06-25
  • 2020-05-23
  • 2011-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 2014-11-26
相关资源
最近更新 更多