【问题标题】:Node.js: Why is the transform function of a Transform stream never getting called?Node.js:为什么永远不会调用转换流的转换函数?
【发布时间】:2020-02-03 15:40:39
【问题描述】:

我正在尝试在 Node.js 12 中编写自定义转换器流。具体来说,我在流(数据库驱动程序)中接收 json 对象并返回转换后的对象。但是我的转换器函数永远不会被调用。我也尝试过覆盖streams.Transform 类。

我想让自定义转换通用,所以我将它封闭在一个闭包中,以便传入一个通用函数:

// transformStream.js
var through2, transformStream;

through2 = require('through2');

transformStream = (handler) => {
  // Through2 in Object Mode
  _transformStream = through2.obj((data, encoding, callback) => {
    console.log(data); // Never called
    this.push(handler(data));
    return callback();
    // also tried:
    // return callback(null, handler(data));
  });

  return _transformStream;
};

module.exports = transformStream;

这里是试验台:

// transformStream.test.js
var jsonStream, through2, transformFunc, transformStream, transformer;

through2 = require('through2');
transformStream = require('./transformStream.js');

// Convert back to a string buffer for console output.
jsonStream = through2.obj(function(chunk, encoding, callback) {
  return callback(null, JSON.stringify(chunk, null, 2) + '\n');
});

transformFunc = function(data) {
  console.log("called with data", data); // Never called!
  data.c = data.a * data.b;
  return data;
};

// deviceStream.pipe(process.stdout)
transformer = transformStream(transformFunc);

transformer.on("error", function(error) {
  return console.error(`Error in Transform: ${error.message}`);
});

transformer.pipe(jsonStream).pipe(process.stdout);

transformer.push({
  a: 1,
  b: 2
});

流似乎可以工作,从不调用实际的转换代码,并且总是只返回原始 json:

{
  A: 1,
  b: 2
}

在控制台中。

我希望看到: { a: 1, b:2, c:2 }

编辑:我还有另一个使用类(绕过2)的版本,具有相同的确切问题:

module.exports = TransformStream = class TransformStream extends Transform {
  constructor(handler, {debug, highWaterMark, ...options}) {
    super({
      highWaterMark: highWaterMark || 10,
      autoDestroy: true,
      emitClose: true,
      objectMode: true,
      debug: true
    });
    this._transform = this._transform.bind(this);
    this.handler = handler;
    this.debug = debug;
    this.options = options;
  }
};

TransformStream.prototype._transform = (data, encoding, callback) => {
  if (this.debug) {
    console.log(data);
  }
  return callback(null, this.handler(data));
};

【问题讨论】:

    标签: javascript node.js stream transform through2


    【解决方案1】:

    显然执行TransformClass.push 调用流的内部输出缓冲区。该流实际上期待一个.write({}) 方法,并适当地调用_transform 函数。

    在测试台上,最终测试应该是:

    transformer.write({
      a: 1,
      b: 2
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      • 2018-05-02
      • 2018-11-12
      • 2021-02-25
      相关资源
      最近更新 更多