javascript - 不使用参数和 this.push 的回调

标签 javascript node.js

我一直在浏览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/

相关文章:

javascript - 序列化错误处理

javascript - react native 错误 : undefined is not an object (evaluating 'Object.keys(dataBlob[sectionID])' )

javascript - Android Webview onLoad 返回错误的高度

javascript - 用 PHPWord setValue 函数替换 html 实体

javascript - 无法从 Handlebars 助手检测到当前语言(i18next.language)?

node.js - 在 WebStorm 中使用任意 NodeJS 单元测试框架进行调试

javascript - 在 vscode 中使用 Node.js 进行调试时,console.timeEnd() 被未知的 constructor.js 欺骗。这是什么?

node.js - 创建 shell 可执行全局 Node 模块

javascript - 使用 JQuery 迭代 DOM

javascript - 使用 Handlebars 'each' 循环访问父级的属性