javascript - 如何重定向基于 "internal state"的流

标签 javascript node.js stream gulp

我正在为 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/

相关文章:

node.js - Namecheap、Node 和 Heroku 上的 SSL

java - 从文件中读取数字,乘以2,写入文件(JAVA)

javascript - 将数据从.net应用程序发送到 Electron 应用程序

node.js - 获取 http ://localhost:3000/socket. io/socket.io.js 404(未找到)

c++ - 如何将文本文件复制到另一个文件?

java - Spliterator 跳过部分文本

javascript - 需要在 javascript 中显示来自数据库的数据

javascript - 是否可以保留单行注释? (用CoffeeScript编写greasemonkey/userscripts)

javascript - JSF h :commandButton not invoked after setting disabled=true in JavaScript 的操作

javascript - 递增数组内对象的计数