title: How exactly stream.Transform works in Node?
body: <p>Below is a code snippet I found online on a blog which entails a simple example in using the stream Transform class to alter data streams and output the altered result. There are some things about this that I don't really understand. </p>
  
  <pre><code>var stream = require('stream');
  var util = require('util');
  
  // node v0.10+ use native Transform, else polyfill
  var Transform = stream.Transform ||
    require('readable-stream').Transform;
  </code></pre>
  
  <p>Why does the program need to check if the this var points to an instance of the Upper constructor? The Upper constructor is being used to construct the upper object below, so what is the reason to check for this? Also, I tried logging options, but it returns null/undefined, so what's the point of that parameter? </p>
  
  <pre><code>function Upper(options) {
    // allow use without new
    if (!(this instanceof Upper)) {
      return new Upper(options);
    }
  </code></pre>
  
  <p>I assume that this Transform.call method is being made to explicitly set the this variable? But why does the program do that, seeing as how Transform is never being called anyway. </p>
  
  <pre><code>  // init Transform
    Transform.call(this, options);
  }
  </code></pre>
  
  <p>After googling the util package, I know that it is being used here to allow Upper to inherit Transform's prototypal methods. Is that right? </p>
  
  <pre><code>util.inherits(Upper, Transform);
  </code></pre>
  
  <p>The function below is what really confuses me. I understand that the program is setting a method on Upper's prototype which is used to transform data being input into it. But, I don't see where this function is being called at all!</p>
  
  <pre><code>Upper.prototype._transform = function (chunk, enc, cb) {
    var upperChunk = chunk.toString().toUpperCase();
    this.push(upperChunk);
    cb();
  };
  
  
  // try it out - from the original code
  var upper = new Upper();
  upper.pipe(process.stdout); // output to stdout
  </code></pre>
  
  <p>After running the code through a debugger, I can see that upper.write calls the aforementioned Upper.prototype._transform method, but why does this happen? upper is an instance of the Upper constructor, and write is a method that doesn't seem to have any relation to the _transform method being applied to the prototype of Upper. </p>
  
  <pre><code>upper.write('hello world\n'); // input line 1
  upper.write('another line');  // input line 2
  upper.end();  // finish
  </code></pre>