Readable
streams are designed to provide a mechanism to easily read data coming into an application from another source. Some common examples of readable streams are:
HTTP responses on the client
HTTP requests on the server
fs
read streams
zlib
streams
crypto
streams
Child processes stdout
and stderr
process.stdin
Readable
streams provide the read([size])
method to read data, where size
specifies the number of bytes to read from the stream. read()
can return a String
object, Buffer
object or null
. Readable
streams also expose the following events:
readable: Emitted when a chunk of data can be read from the stream.
data: Similar to readable
, except that when data
event handlers are attached, the stream is turned into flowing mode, and the data
handler is called continuously until all data has been drained.
end: Emitted by the stream when data will no longer be provided.
close: Emitted when the underlying resource, such as a file, has been closed.
error: Emitted when an error occurs in receiving data.
Readable
stream objects also provide a number of functions that allow you to read and manipulate them. Table 5.4 lists the methods available on Readable
stream objects.
To implement your own custom Readable
stream object, you need to first inherit the functionality for Readable
streams. The simplest way to do this is to use the following code, which uses the util
module’s inherits()
method:
var util = require('util'),
util.inherits(MyReadableStream, stream.Readable);
Then you create an instance of the object call:
stream.Readable.call(this, opt);
You will also need to implement a _read()
method that calls push()
to output the data from the Readable
object. The push()
call should push either a String
, Buffer
, or null
.
The code in Listing 5.6 illustrates the basics of implementing and reading from a Readable
stream. Notice that the Answers()
class inherits from Readable
and then implements the Answers.prototye._read()
function to handle pushing data out. Also notice that on line 18, a direct read()
call reads the first item from the stream, and then the data
event handler defined on lines 19–21 reads the rest of the items. Figure 5.6 shows the output for Listing 5.6.
01 var stream = require('stream'),
02 var util = require('util'),
03 util.inherits(Answers, stream.Readable);
04 function Answers(opt) {
05 stream.Readable.call(this, opt);
06 this.quotes = ["yes", "no", "maybe"];
07 this._index = 0;
08 }
09 Answers.prototype._read = function() {
10 if (this._index > this.quotes.length){
11 this.push(null);
12 } else {
13 this.push(this.quotes[this._index]);
14 this._index += 1;
15 }
16 };
17 var r = new Answers();
18 console.log("Direct read: " + r.read().toString());
19 r.on('data', function(data){
20 console.log("Callback read: " + data.toString());
21 });
22 r.on('end', function(data){
23 console.log("No more answers.");
24 });
18.217.251.56