I know the way to make a GET request to a URL using the request
module. Eventually, the code just prints the GET response within the command shell from where it has been spawned.
How do I store these GET response in a local variable so that I can use it else where in the program?
This is the code i use:
var request = require("request");
request("http://www.stackoverflow.com", function(error, response, body) {
console.log(body);
});
The easiest way (but it has pitfalls--see below) is to move
body
into the scope of the module.However, this may encourage errors. For example, you might be inclined to put
console.log(body)
right after the call torequest()
.This will not work because
request()
is asynchronous, so it returns control beforebody
is set in the callback.You might be better served by creating
body
as an event emitter and subscribing to events.Another option is to switch to using promises.