我一直在浏览nodeschool.io 的教程,并被一个涉及流的特定问题所困扰。这是给定的解决方案。
我主要对上面的变量以及为什么我需要调用 this.push 感到困惑。我不能只通过回调函数(next())传递数据变量吗?
如果能逐行解释这里发生的事情,我们将不胜感激。
var http = require('http');
var fs = require('fs');
var through2 = require('through2');
var upper = through2(function(data, _, next) {
data = data.toString().toUpperCase();
this.push(data);
next();
});
http.createServer(function(req,res) {
if (req.method == 'POST') {
req.pipe(upper).pipe(res);
}
}).listen(process.argv[2]);
最佳答案
这就是 through2 函数的 API 的工作原理。来自 documentation
The transformFunction must have the following signature: function (chunk, encoding, callback) {}. A minimal implementation should call the callback function to indicate that the transformation is done, even if that transformation means discarding the chunk.
To queue a new chunk, call this.push(chunk)—this can be called as many times as required before the callback() if you have multiple pieces to send on.
显然, this.push 的原因是为了让您能够轻松处理需要推送大量 block 的情况。
for(var i=1; i<=10; i++){
this.push( /**/ )
}
也就是说,根据文档,您还可以根据需要将 block 传递给回调:
Alternatively, you may use callback(err, chunk) as shorthand for emitting a single chunk or an error.
我无法测试,但我猜你想要类似的东西
var upper = through2(function(data, _, next) {
data = data.toString().toUpperCase();
next(null, data);
});
关于javascript - 不使用参数和 this.push 的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31861681/