【问题标题】:Node.Js Through2- modifying streamNode.Js Through2-修改流
【发布时间】:2015-04-08 01:06:28
【问题描述】:

我正在使用through2 试验 Node.js 流。我有一个流是 index.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 流的任何建议?

【问题讨论】:

    标签: node.js stream node.js-stream


    【解决方案1】:

    如果您想保留 forEach() 而不是常规的 for 循环,forEach() 接受 second argument,这是所需的 this 上下文:

    blah.forEach(function(element) {
      this.push("-------");
      this.push(element):
    }, this);
    

    您也可以始终使用更通用的“自我”解决方法:

    var self = this;
    blah.forEach(function(element) {
      self.push("-------");
      self.push(element):
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      相关资源
      最近更新 更多