【发布时间】: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