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