How to implement a basic example of node Stream.Readable?

I am trying to learn threads and I have a bit of a problem to get it working correctly.

In this example, I just would like to push a static object on the stream and channel to respond to my servers.

Here is what I still have, but a lot of this does not work. If I could just get a stream for output to the console, I can figure out how to pass it in response.

var Readable = require('stream').Readable; var MyStream = function(options) { Readable.call(this); }; MyStream.prototype._read = function(n) { this.push(chunk); }; var stream = new MyStream({objectMode: true}); s.push({test: true}); request.reply(s); 
+8
javascript stream
source share
1 answer

There are several problems with your current code.

  • The request stream is most likely a buffer mode stream: this means that you cannot write objects to it. Fortunately, you do not pass parameters to the Readable constructor, so your error does not cause any problems, but semantically it is incorrect and will not lead to the expected results.
  • You invoke the Readable constructor, but do not inherit the prototype properties. You must use util.inherits() to subclass Readable .
  • The chunk variable is not defined anywhere in your sample code.

Here is a working example:

 var util = require('util'); var Readable = require('stream').Readable; var MyStream = function(options) { Readable.call(this, options); // pass through the options to the Readable constructor this.counter = 1000; }; util.inherits(MyStream, Readable); // inherit the prototype methods MyStream.prototype._read = function(n) { this.push('foobar'); if (this.counter-- === 0) { // stop the stream this.push(null); } }; var mystream = new MyStream(); mystream.pipe(process.stdout); 
+8
source share

All Articles