A Transform
stream extends the Duplex
stream but modifies the data between the Writable
stream and the Readable
stream. This stream type can be extremely useful when you need to modify data from one system to another. Some examples of Transform
streams are:
zlib
stream
crypto
streams
A major difference between the Duplex
and the Transform
streams is that for Transform
streams, you do not need to implement the _read()
and _write()
prototype methods. These are provided as pass-through functions. Instead, you implement the _transform(chunk, encoding, callback)
and _flush(callback)
methods. The _transform()
method should accept the data from write()
requests, modify it, and push out the modified data.
The code in Listing 5.9 illustrates the basics of implementing a Transform
stream. The stream accepts JSON strings, converts them to objects, and then emits a custom event named object
that sends the object to any listeners. The _transform()
function also modifies the object to include a handled
property and then sends on a string form. Notice that lines 18–21 implement the object
event handler function, which displays certain attributes. Figure 5.9 shows the output for Listing 5.9. Notice that the JSON strings now include the handled
property.
01 var stream = require("stream");
02 var util = require("util");
03 util.inherits(JSONObjectStream, stream.Transform);
04 function JSONObjectStream (opt) {
05 stream.Transform.call(this, opt);
06 };
07 JSONObjectStream.prototype._transform = function (data, encoding, callback) {
08 object = data ? JSON.parse(data.toString()) : "";
09 this.emit("object", object);
10 object.handled = true;
11 this.push(JSON.stringify(object));
12 callback();
13 };
14 JSONObjectStream.prototype._flush = function(cb) {
15 cb();
16 };
17 var tc = new JSONObjectStream();
18 tc.on("object", function(object){
19 console.log("Name: %s", object.name);
20 console.log("Color: %s", object.color);
21 });
22 tc.on("data", function(data){
23 console.log("Data: %s", data.toString());
24 });
25 tc.write('{"name":"Carolinus", "color": "Green"}'),
26 tc.write('{"name":"Solarius", "color": "Blue"}'),
27 tc.write('{"name":"Lo Tae Zhao", "color": "Gold"}'),
28 tc.write('{"name":"Ommadon", "color": "Red"}'),