I'm new to javascript and node.js and I have been really struggling to figure this scoping problem out. The code below makes a simple get request and displays the body of the webpage to the console - no problems there.
function makeGETRequest(host, path, headers) {
var options = {
hostname: host,
port: 8000,
path: path,
method: 'GET',
headers: headers
};
var request = http.request(options, function(response) {
response.on('data', function(body) {
console.log('Body: ' + body);
});
});
request.end();
}
What I can't seem to do is get any information out of the function declared inside http.request. If I want to save the body to a variable that I've declared in makeGETRequest() and then return it, it will be undefined because it goes out of scope. Creating a global variable and using that instead does not solve the problem.
ex.
function makeGETRequest(host, path, headers) {
var siteBody;
var options = {
hostname: host,
port: 8000,
path: path,
method: 'GET',
headers: headers
};
var request = http.request(options, function(response) {
response.on('data', function(body) {
console.log('Body: ' + body);
siteBody = body; //works as long as I don't exit the scope of the function
});
});
request.end();
return body; //returns undefined
}
How do I get information body or otherwise out of these functions so that I can use the information in makeGETrequest() and then return it?