这是 nodeschool.io 冒险流类(class)练习的解决方案。
我很难理解这条线是如何工作的
req.pipe(upper).pipe(res)
如果能深入解释内部发生的情况,我们将不胜感激。
据我了解,请求将其信息发送到上层进行转换,但是当它通过回调返回时,第二个管道是否调用了返回值?
var http = require('http');
var fs = require('fs');
var through2 = require('through2');
var upper = through2(function(data, _, next) {
data = data.toString().toUpperCase();
next(null,data);
});
http.createServer(function(req,res) {
if (req.method == 'POST') {
req.pipe(upper).pipe(res);
}
}).listen(process.argv[2]);
最佳答案
.pipe
是或多或少的糖分
req.on('data', function(chunk) {
next_stream.write(chunk);
});
// also handle the 'end' and 'close' events
并返回 next_stream
,因此可以链接 .pipe
。 res
是一个可写流,表示浏览器读取的流,只需要将其写入并关闭以便响应使其到达浏览器,即 .pipe
我想在这种情况下没有真正调用“完成”响应的“回调”是毫无值(value)的。浏览器只是在我们将数据写入 res
时获取数据,并在 res
关闭时停止加载更多数据。
查看 the .pipe
method 的 NodeJS 源代码
关于javascript - 难以理解NodeJS中的回调方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31866409/