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);
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.
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.
For example, in a Node. js based HTTP server, request is a readable stream and response is a writable stream.
There are a couple of issues with your current code.
Readable
constructor so your mistake doesn't cause any trouble, but semantically this is wrong and will not produce the expected results.Readable
, but don't inherit the prototype properties. You should use util.inherits()
to subclass Readable
.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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With