简体   繁体   English

node.js中的through2和native Transform stream有什么区别?

[英]What is the difference between through2 and native Transform stream in node.js?

In the through2 docs , it says:through2 docs中,它说:

A tiny wrapper around Node.js streams.Transform (Streams2/3) to avoid explicit subclassing noise.围绕 Node.js 流的小型包装器。转换(Streams2/3)以避免显式子类化噪声。

What is meant by that?这是什么意思? What is this " subclassing noise "?这是什么“子类噪音”?

Common implementation on transform stream looks like:变换 stream 的常见实现如下所示:

ES5 syntax ES5 语法

const { Transform } = require('stream');
const util = require('util');

function MyTransform(options) {
  if (!(this instanceof MyTransform))
    return new MyTransform(options);
  Transform.call(this, options);
}
util.inherits(MyTransform, Transform);

MyTransform.prototype._transform = function (chunk, enc, cb) {
  // do some data transformation
  this.push(chunk);
  cb();
};

ES6 syntax ES6 语法

const { Transform } = require('stream');

class MyTransform extends Transform {
  constructor(options) {
    super(options);
  }

  _transform(chunk, encoding, cb) {
    // do some data transformation
    this.push(chunk)
    cb()
  }
}

As you can see, to implement transform stream you have to write some boilerplate code, like extending Transform interface etc.如您所见,要实现变换 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 您必须编写一些样板代码,例如扩展 Transform 接口等。

By using through2 you just write your transformation function.通过使用 through2,您只需编写转换 function。 Profit.利润。

In the through2 docs it also says (nowadays):在 through2 文档中它还说(现在):

Since Node.js introduced Simplified Stream Construction, many uses of through2 have become redundant.自从 Node.js 引入了简化的 Stream 构造后,through2 的许多用途就变得多余了。

The example by Rezvan above would then become:上面 Rezvan 的示例将变为:

const { Transform } = require('stream');

return new Transform({
  transform(chunk, encoding, cb) {
    // do some data transformation
    this.push(chunk);
    cb();
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM