It's because the operation is asynchronous. This means that simpleTest returns long before the http.get() response arrives.
Any code that needs the response must be invoked from in the callback. In your case, there could be multiple invocations of the data callback, so you need to handle it inside the end callback.
'use strict';
var http = require('http');
function simpleTest() {
http.get("http://google.com/", function (res) {
var html = '';
res.on('data', function (chunk) {
html += chunk;
});
res.on('end', function () {
console.log(html);
});
});
}
simpleTest();
If you don't want to hardcode the console.log(), you can put it in a function, and pass the function to simpleTest(). This makes it much more generic.
'use strict';
var http = require('http');
function simpleTest(fn) {
http.get("http://google.com/", function (res) {
var html = '';
res.on('data', function (chunk) {
html += chunk;
});
res.on('end', function () {
fn(html);
});
});
}
simpleTest(function(data) {
console.log(data);
});
So here we passed a function to the fn parameter, and invoked the fn parameter inside the end callback.
When we invoke it, we pass the final html value, and the callback receives it in its data parameter.
These are very common patterns, so it would be a good idea to get familiar with them.