Transform Stream in NodeJS using es6 classes

I was looking for some information on how to use transform stream api to convert some incoming data into csv and i noticed that most examples on the web are using prototypal approach. In most cases I would agree that prototypes are more explicit and make more sense but in some cases es6 classes are just nicer to use and they can make your code more readable and make you like js just a little bit more.…

I will start by showing an original function i wrote.

Here we define a function getHeaders then we use inherits passing both new faction and original Transform class.

On line 12 we overwrite a method _transform that we getHeaders() inherited from Transform.

One thing that seems unclear and confusing to me is the fact that we create a function and then make it to inherit from class and thus converting it to class as well (I know everything in js is an object). But this bait and switch makes for inconsistent api in this case.

In contrast we can do the same thing with es6 classes.

on line 3 we clearly define a class and we also clearly define a relations between to classes.

on line 4 we call a contractor assigning all props and methods of Transform to toCSV.

on line 7 we overwrite _transform(chunk, enc, done) method providing a custom logic on how to handle chunks.

I also think it makes easy to modify behavior of this class depending on args passed in during creation of this class. For instance we can define default properties inside the constructor of toCSV class to later change the way we handle data.

In this example we set a default argument tsv equal to false this argument can be overwritten when we create this class with keyword “new” for example new toCSV(tsv=true)

Finally we can make a use of this new class by piping a stream through it.

and we can send params that will modify behavior of the instance of this class.

I am just learning this stuff…

Thank you