8

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);
}); 
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
SheikhZayed
  • 91
  • 1
  • 2
  • 7
  • Try to see this question before move: http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – vanadium23 May 27 '15 at 14:48
  • `body` is already a local variable within the function that's holding the response. You can copy the value to another variable declared before the request. But, because it's performed asynchronously, you won't have a guarantee that the request completed before attempting to use it beyond what's invoked inside of the `function (error, response, body)`. – Jonathan Lonowski May 27 '15 at 14:53

1 Answers1

20

The easiest way (but it has pitfalls--see below) is to move body into the scope of the module.

var request = require("request");
var body;


request("http://www.stackoverflow.com", function(error, response, data) {
    body = data;
});

However, this may encourage errors. For example, you might be inclined to put console.log(body) right after the call to request().

var request = require("request");
var body;


request("http://www.stackoverflow.com", function(error, response, data) {
    body = data;
});

console.log(body); // THIS WILL NOT WORK!

This will not work because request() is asynchronous, so it returns control before body is set in the callback.

You might be better served by creating body as an event emitter and subscribing to events.

var request = require("request");
var EventEmitter = require("events").EventEmitter;
var body = new EventEmitter();


request("http://www.stackoverflow.com", function(error, response, data) {
    body.data = data;
    body.emit('update');
});

body.on('update', function () {
    console.log(body.data); // HOORAY! THIS WORKS!
});

Another option is to switch to using promises.

Trott
  • 66,479
  • 23
  • 173
  • 212