javascript - 转换流 Node js中的回调函数

标签 javascript node.js stream transform

这是一个转换流 Node 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

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

最佳答案

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

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

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

要对新 block 进行排队,请调用 this.push(chunk) - 如果您有多个要发送的 block ,则可以在回调()之前根据需要多次调用此函数。

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

关于javascript - 转换流 Node js中的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42946669/

相关文章:

c++ - 如何创建一个while循环,该循环继续循环直到在C++中输入了 'using streams'键?

javascript - RequireJS 加载我的 JS 文件,但在使用它们时触发错误

javascript - 内容居中,标题从左到中

node.js - 如何将现有的 node.js 模块导入 Intellij IDEA?

c# - 是否有与 StreamReader 的 Peek 方法等效的异步方法?

node.js - Nodejs : Performance issues parsing CSV and Zip

javascript - 从Google Earth插件中的kmlObject获取kml字符串

javascript - 什么时候在 js 中使用 == 而不是 === 是个好主意?

node.js - 找不到模块 "express"- docker-compose nodejs 服务

javascript - Nodejs Q Promise catch 从未用 Passport js 调用