title: Nodejs readable stream pipe to response
body: <p>I have to maintain a legacy code. The basics: it should handle incoming stream (audio and/or video). The 3rd party device send the stream when it's requested. Then a client should consume it.</p>
  
  <p>The code was unfinished, but for me, seems good.
  NodeJS version is the latest (atm): 8.9.4</p>
  
  <p>// init.js (the main js file)</p>
  
  <pre><code>global.readStream = new readStream();
  </code></pre>
  
  <p>The read stream object look like this old one:
  // readStream object</p>
  
  <pre><code>var Readable = require('stream').Readable;
  var util = require('util');
  
  function myReadStream() {
    Readable.call(this);
    this.data = null;
  }
  util.inherits(myReadStream, Readable);
  
  myReadStream.prototype.addData = function (newData) {
      this.data = newData;
      console.log('new data: ', this.data);
  };
  
  myReadStream.prototype._read = function () {
    this.push(this.data);
  };
  </code></pre>
  
  <p>So, the two endpoint:</p>
  
  <pre><code>app.get('incomingdata', function (req, res) {
       myReadStream.addData = res.newIncomingData; 
       // just writing the stream data directly
       console.log('incoming: ', res.newIncomingData);
  });
  
  app.get('outgoingData', function (req, res) {
       myReadStream
    .on('readable', function () {
      var obj;
      while (null !== (obj = myReadStream.read())) {
        myReadStream.pipe(res); // direct pipe to res
        // alternative idea: res.send(obj);
        // alternative #2: res.write(obj);
        console.log('outgoing: ', obj);
      }
    });
  });
  </code></pre>
  
  <p>The result is, the call of "outgoingData" always repeat just one stage of the readStream data (what was recently feeded before the outgoing data call) but not refreshing...</p>
  
  <p>E.g.:</p>
  
  <pre><code>Incoming: &lt;Buffer 00 e3 ff ab a2 ....&gt;
  new data: &lt;Buffer 00 e3 ff ab a2 ....&gt;
  Incoming: &lt;Buffer 01 3b ca c1 b0 ....&gt;
  new data: &lt;Buffer 01 3b ca c1 b0 ....&gt;
  Outgoing: &lt;Buffer 01 3b ca c1 b0 ....&gt;
  Incoming: &lt;Buffer 99 fa e8 77 00 ....&gt;
  new data: &lt;Buffer 99 fa e8 77 00 ....&gt;
  Outgoing: &lt;Buffer 01 3b ca c1 b0 ....&gt;
  Incoming: &lt;Buffer ef b0 00 22 33 ....&gt;
  new data: &lt;Buffer ef b0 00 22 33 ....&gt;
  Outgoing: &lt;Buffer 01 3b ca c1 b0 ....&gt;
  Incoming: &lt;Buffer 25 7b 91 aa 00 ....&gt;
  new data: &lt;Buffer 25 7b 91 aa 00 ....&gt;
  Outgoing: &lt;Buffer 01 3b ca c1 b0 ....&gt;
  </code></pre>
  
  <p>I only have experience with Socket.Io, not much in readable and writeable. As far as I know, this code was developed ~1.5y ago, for version 4.x.
  The code seems good, but miss something. Any idea what's wrong, how can I correct it?</p>
  
  <p>(p.s.: I don't like to maintain legacy code)</p>