我正在使用 through2
尝试 Node.js 流。我有一个索引.html 文件的流,我试图通过在每一行添加 -------
逐行修改 index.html 内容。我有:
indexHTML
.pipe(through2.obj(function(obj, enc, next) {
blah = obj.contents.toString().split('\n');
blah.forEach(function(element) {
this.push("-------");
this.push(element):
});
next();
})).pipe(process.stdout);
我目前遇到的问题是 this.push()
在 blah.forEach()
数组方法中不可用。关于如何修改index.html流有什么建议吗?
如果您想保留 forEach()
而不是常规的 for 循环,forEach()
接受 second argument这是所需的 this
上下文:
blah.forEach(function(element) {
this.push("-------");
this.push(element):
}, this);
您还可以始终使用更通用的“ self ”解决方法:
var self = this;
blah.forEach(function(element) {
self.push("-------");
self.push(element):
});
我是一名优秀的程序员,十分优秀!