【问题标题】:callback function in transform stream node js转换流节点js中的回调函数
【发布时间】:2017-03-22 08:50:31
【问题描述】:

它是一个简单的转换流节点js的例子。

代码:

const { Transform } = require('stream');

const transtream = new Transform({
    transform(chunk, encoding, callback){
        this.push(chunk.toString().toUpperCase());
        callback()
    }
});

process.stdin.pipe(transtream).pipe(process.stdout);

这很好用:

Input: hi this is me
Output: HI THIS IS ME
Input: hi this is me again
Output: HI THIS IS ME AGAIN

现在如果我不调用回调函数,这个程序就不能像以前那样工作了。

新代码:

const { Transform } = require('stream');

const transtream = new Transform({
    transform(chunk, encoding, callback){
        this.push(chunk.toString().toUpperCase());
        //callback()
    }
});

process.stdin.pipe(transtream).pipe(process.stdout);

现在,当我提供输入时,它第一次工作,然后停止转换数据。所以没有输出第二个输入。

Input: hi this is me
Output: HI THIS IS ME
Input: hi this is me again
Input: hey

问题:为什么需要回调?为什么程序在不被调用时会改变行为?

【问题讨论】:

  • 你问为什么需要回调?
  • 你能澄清一下问题是什么吗?
  • 数据读成流的时候是不是回调函数push了?

标签: javascript node.js stream transform


【解决方案1】:

我只是复制粘贴 through2 npm 模块的部分文档。

通常当你想在 node js 中玩流时,最好使用 npm 模块。

transformFunction 必须具有以下签名:function (chunk, encoding, callback) {}。一个最小的实现应该调用回调函数来指示转换已经完成,即使该转换意味着丢弃块。

要对新块进行排队,请调用 this.push(chunk) - 如果您有多个要发送的块,则可以在 callback() 之前调用任意多次。

或者,您可以使用 callback(err, chunk) 作为发出单个块或错误的简写。

【讨论】:

    【解决方案2】:

    将其视为 ExpressJS 中的中间件如何工作,如果您不提供对 next() 的调用,则中​​间件不会将控制权移交给您的 ExpressJS 程序中的下一个中间件,这与此回调函数的工作方式相同。如果您不调用 callback() 方法,就好像您尚未将该数据块的控制权转移到管道中的下一个流处理程序。

    如果 callback() 的名称令人困惑,只需将其更改为 next() 即可为您提供与 ExpressJS 中相同的思维模型。

    与 through2 相比,使用本机 Stream Transforms 并没有犯罪,唯一的缺点是,如果底层 Node Stream API 发生更改,您的代码可能会中断,而这不一定会影响 NPM 模块。

    【讨论】:

      猜你喜欢
      • 2018-07-15
      • 1970-01-01
      • 2023-03-23
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 2018-10-06
      相关资源
      最近更新 更多