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...
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.