How do I implement a basic node Stream.Readable example?
javascript, node.js, stream
Solution
There are a couple of issues with your current code.
- 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.
- You call the constructor of `Readable`, but don't inherit the prototype properties. You should use `util.inherits()` to subclass `Readable`.
- 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);
Problem
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); ```