Writable
streams are designed to provide a mechanism to write data into a form that can easily be consumed in another area of code. Some common examples of Writable
streams are:
HTTP requests on the client
HTTP responses on the server
fs
write streams
zlib
streams
crypto
streams
TCP sockets
Child process stdin
process.stdout
and process.stderr
Writable
streams provide the write(chunk, [encoding], [callback])
method to write data into the stream, where chunk
contains the data to write; encoding
specifies the string encoding, if necessary; and callback
specifies a callback function to execute when the data has been fully flushed. The write()
function returns true
if the data was written successfully. Writable
streams also expose the following events:
drain: After a write()
call returns false
, emitted to notify listeners when it is okay to begin writing more data.
finish: Emitted when end()
is called on the Writable
object, all data is flushed, and no more data will be accepted.
pipe: Emitted when the pipe()
method is called on a Readable
stream to add this Writable
as a destination.
unpipe: Emitted when the unpipe()
method is called on a Readable
stream to remove this Writable
as a destination.
Writable
stream objects also provide a number of methods that you can write and manipulate. Table 5.5 lists the methods available on Writable
stream objects.
To implement your own custom Writable
stream object, you need to first inherit the functionality for Writable
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(MyWritableStream, stream.Writable);
Then you create an instance of the object call:
stream.Writable.call(this, opt);
You also need to implement a _write(data, encoding, callback)
method that stores the data for the Writable
object. The code in Listing 5.7 illustrates the basics of implementing and writing to a Writable
stream. Figure 5.7 shows the output for Listing 5.7.
01 var stream = require('stream'),
02 var util = require('util'),
03 util.inherits(Writer, stream.Writable);
04 function Writer(opt) {
05 stream.Writable.call(this, opt);
06 this.data = new Array();
07 }
08 Writer.prototype._write = function(data, encoding, callback) {
09 this.data.push(data.toString('utf8'));
10 console.log("Adding: " + data);
11 callback();
12 };
13 var w = new Writer();
14 for (var i=1; i<=5; i++){
15 w.write("Item" + i, 'utf8'),
16 }
17 w.end("ItemLast");
18 console.log(w.data);