I'm new in node.js and java script, i cant find meaning of this ".on" keyword. when i change it with another word code failed.
var req = http.get("http://www.google.com", function(res) { console.log("Got response: " + res.statusCode); res.on('data', function (chunk) { }); }).on('error', function(e) { console.log("Got error: " + e.message); });
The on method binds an event to a object. It is a way to express your intent if there is something happening (data sent or error in your case) , then execute the function added as a parameter. This style of programming is called Event-driven programming.
res. on('data', ...) is how you register a listener for the data event and the data event is the primary way that you receive data from the incoming stream. This listener will be called one or more times with chunks of arriving data.
Request and Response object both are the callback function parameters and are used for Express. js and Node. js. You can get the request query, params, body, headers, and cookies. It can overwrite any value or anything there.
The on method binds an event to a object.
It is a way to express your intent if there is something happening (data sent or error in your case) , then execute the function added as a parameter. This style of programming is called Event-driven programming. You might want to look it up in the Wikipedia
In node.js, there is a class called EventEmitter that provides you with all the code that you need for basic events if you decide to use them in your own code (which I would strongly recommend in the case of node.js). Docs for node.js EventEmitter are here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With