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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.

You Might Also Like