javascript - Node Stream: Not passing Callback Function a Value -
javascript - Node Stream: Not passing Callback Function a Value -
i working on nodeschool.io's learnyounode http client exercise.
this task:
write programme performs http request url provided first command-line argument. write string contents of each "data" event response new line on console (stdout).
my solution was:
var http = require("http"); var url = process.argv[2]; http.get(url, function(res){ res.setencoding('utf8'); res.on('data', function(data){ console.log(data); }) });
this worked, curious why suggested solution works. how console.log , console.error using data
or error
objects. don't appear passed callback function.
var http = require('http') http.get(process.argv[2], function (response) { response.setencoding('utf8') response.on('data', console.log) response.on('error', console.error) })
by using response.on('data', console.log)
, registering event listener trigger console.log()
function it's callback. response object event emitter, , when http.get
request receives info remote server emits 'data' event picked listener. event implicitly passes received info first parameter console.log
callback function on listener. same process holds true 'error' event.
javascript node.js callback
Comments
Post a Comment