vendredi 26 juin 2015

Parameters coming from nowhere

var streams = require('stream');
var util = require('util');
util.inherits(JSONObjectStream, streams.Transform);

function JSONObjectStream(opt){
    streams.Transform.call(this, opt);
}

JSONObjectStream.prototype._transform = function(data, encoding, callback){
    object = data ? JSON.parse(data.toString()) : "";
    this.emit("object", object);
    object.handled = true;
    this.push(JSON.stringify(object));
    callback();
};

JSONObjectStream.prototype._flush = function(cb){
    cb();
};

var tc = new JSONObjectStream();

tc.on("object", function(object){
    console.log("Name: %s", object.name);
    console.log("Color: %s", object.color);
});

tc.on("data", function(data){
    console.log("Data: %s", data.toString());
});

tc.write('{"name": "Carolinus", "color": "Green"}');
tc.write('{"name": "Solarius", "color": "Blue"}');

I have a bunch questions about the code above. I've tested it out, and it does work perfectly.

First question: How does the "opt" parameter get its value in the function JSONObjectStream(opt)? I do not see any value being passed when I create the "tc" object.

Second Question: When I prototype the transform method, from where does the "callback" parameter receive its value? I do not see a value being passed to it when I call the method with tc.write().

Third Question: What is the flush() method's use in this program? I do not see it being called anywhere in the code. And if it is called somewhere, from where its "cb" parameter receive its value?

Fourth Question: How is the variable "object" able to be declared? It doesn't has neither a var nor a this before it.

I got this code from a book, but I can't figure out how it works.

Thanks for taking your time to check it out!




Aucun commentaire:

Enregistrer un commentaire