In this article I will try to surface dive on some of the basic concept of Nodejs called "Streams and Events". So first thing first :

What is Stream? Basically stream is a list of data coming in asynchronous fashion from server, API, etc.

In order to understand bits and bolts of the topic at hand we need to build and understand the backbones and building blocks for them, which are "Callback" and "Events", so What is Callback?

Callbacks are away to write asynchronous non blocking code (Request/Reply Pattern) 


fnExample(param, function(err, results){ 
// custom logic... 

Another way provided by Nodejs to achieve "asynchronous non blocking code" is via Events (Publisher/Subscriber Pattern). So as we know what are events lets see the example.


var results = fnExample(param); 

results.on('start', function(data){ // start is custom event name 

results.on('done', function(data){// done is custom event name 
results.on('end', function(data){// end is custom event name 


Callbacks Events 
As its Request/Reply pattern it waits till we get all the results back and then proceeds with the callback function invocation.As it’s a Publisher/Subscriber pattern, even with first result item depenidng on the event subscribed to, the function invocation starts. 
As it waits till all the results are arrives, it stores the results in memory, so memory consumption is more. As it kick starts the function as and when the  data arrives there is no storing of results in memory leading to zero memory consumption. 
This is basically “Either error or results” type. If we look at the signature of callback function, the first param is err (nodejs convention), which suggest if there err is set then there is no result. This is basically “Partial results before error” type. If we look at the signature of how “on” function over EventEmitter instance is called, it has “error” event separate for every function. So if we have “done” event called multiple times before “error” event we can have at least partial results. 



Now after basic idea of what Callbacks and Events are lets jump into the "trunk of the tree" : EventEmitter

EventEmitter Class : This is provided by Nodejs to build “Event” driven interface. 


Publisher Subscriber 
emitter.emit(event, [args]); emitter.on(event, resultArgs); 


There are two ways you can implement EventEmitters to build our streams

  1. By Composition (new-ing up EventEmitters Example : new EventEmitter()) 
  2. By Inheritance (Inheriting from EventEmitters) 

Please find the code for above two approaches @ 

 In code for Composition approach “getResource” and for Inheritance approach “Resource” are streams. 

Danke :)