Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement a basic node Stream.Readable example?

I'm trying to learn streams and am having a little bit of an issue getting it to work right.

For this example, I'd simply like to push a static object to the stream and pipe that to my servers response.

Here's what I have so far, but a lot of it doesn't work. If I could even just get the stream to output to console, I can figure out how to pipe it to my 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);
like image 292
doremi Avatar asked Dec 20 '13 17:12

doremi


People also ask

How do you implement a readable stream?

To implement a readable stream, we require the Readable interface, and construct an object from it, and implement a read() method in the stream's configuration parameter: const { Readable } = require('stream'); const inStream = new Readable({ read() {} }); There is a simple way to implement readable streams.

How do you read from a readable stream in node JS?

read() Method. The readable. read() method is an inbuilt application programming interface of Stream module which is used to read the data out of the internal buffer. It returns data as a buffer object if no encoding is being specified or if the stream is working in object mode.

Which of the following is an example of a readable stream in node JS?

For example, in a Node. js based HTTP server, request is a readable stream and response is a writable stream.


1 Answers

There are a couple of issues with your current code.

  1. The request stream is most likely a buffer mode stream: this means that you can't write objects into it. Fortunately, you don't pass through the options to the Readable constructor so your mistake doesn't cause any trouble, but semantically this is wrong and will not produce the expected results.
  2. You call the constructor of Readable, but don't inherit the prototype properties. You should use util.inherits() to subclass Readable.
  3. The chunk variable isn't defined anywhere in your code sample.

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);
like image 59
Paul Mougel Avatar answered Oct 05 '22 06:10

Paul Mougel