Piping Readable Streams to Writable Streams

One of the coolest things you can do with stream objects is chain Readable streams to Writable streams by using the pipe(writableStream, [options]) function. This does exactly what the name implies: It inputs the output from the Readable stream directly into the Writable stream. The options parameter accepts an object with the end property set to true or false. When end is true, the Writable stream ends when the Readable stream ends. This is the default behavior. For example:

readStream.pipe(writeStream, {end:true});

You can also break the pipe programmatically by using the unpipe(destinationStream) option. The code in Listing 5.10 implements a Readable stream and a Writable stream and then uses the pipe() function to chain them together. To show you the basic process, the data input from the _write() method is output to the console in Figure 5.10.

Listing 5.10 stream_piped.js: Piping a Readable stream into a Writable stream


01 var stream = require('stream'),
02 var util = require('util'),
03 util.inherits(Reader, stream.Readable);
04 util.inherits(Writer, stream.Writable);
05 function Reader(opt) {
06   stream.Readable.call(this, opt);
07   this._index = 1;
08 }
09 Reader.prototype._read = function(size) {
10   var i = this._index++;
11   if (i > 10){
12     this.push(null);
13   } else {
14     this.push("Item " + i.toString());
15   }
16 };
17 function Writer(opt) {
18   stream.Writable.call(this, opt);
19   this._index = 1;
20 }
21 Writer.prototype._write = function(data, encoding, callback) {
22   console.log(data.toString());
23   callback();
24 };
25 var r = new Reader();
26 var w = new Writer();
27 r.pipe(w);


Image

Figure 5.10 Output of stream_piped.js, implementing stream piping.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.195.29