What Is the Difference Between Through2 and Native Transform Stream in Node. Js?

In the through2 docs, it says:

A tiny wrapper around Node.js streams.Transform (Streams2/3) to avoid explicit subclassing noise.

What is meant by that? What is this "subclassing noise"?

2 Answers

In the through2 docs it also says (nowadays):

Since Node.js introduced Simplified Stream Construction, many uses of through2 have become redundant.

The example by Rezvan above would then become:

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

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

Common implementation on transform stream looks like:

ES5 syntax

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

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.

By using through2 you just write your transformation function. Profit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest